今天在部署.Net 5開發的應用時,遇到了以下的錯誤。
ERROR 2021-02-25 20:39:28,460 [16 ] spNetCore.Antiforgery.DefaultAntiforgery - An exception was thrown while deserializing the token. Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {238a0f63-439d-4e88-883b-002c09902988} was not found in the key ring. at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData) at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken) --- End of inner exception stack trace --- at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken) at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)
跑到Google上查了一下,說是ASP.net Core防止跨站請求偽造攻擊機制的原因,排查了程序應該不是程序的問題,后來在一篇國外的帖子上看到說,需要定義Machine Key,在IIS7.5以下或是想給某個應用專用的話,需要在Web.Config中定義。否則直接在IIS服務器層極定義即可。
點擊進去后,如果應用全服務器的話,需要選中“Automatically generate at runtime” & "Automatically generate at runtime"兩個復選框。
同時,還需要將應用程序的"Load User Profile“屬於設置為”True“。
這樣就基本解決了我遇到的問題,記錄一下,以備查。