发布项目后出现异常 "System.Security.Cryptography.CryptographicException"

Exception "System.Security.Cryptography.CryptographicException" after Publishing project

每次我将我的 Blazor Server 项目发布到我的网站域并打开该网站时,都会发生此异常,Google 搜索几乎没有帮助:

它说 AppState.cs: line 21,所以这是它的代码行:

调试本地主机时不会发生此异常。当我从我网站上的浏览器中删除 localStorage 并刷新时,一切正常。但我不希望我的客户有这个例外,并且每次我发布时都必须告诉他们删除本地存储。

我的Program.cs如有必要:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor().AddCircuitOptions(options => options.DetailedErrors = true);
builder.Services.AddHttpClient();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters.ValidateIssuerSigningKey = true; // Validér secret key for JWT
        options.TokenValidationParameters.ValidateLifetime = false; // Validér ikke Lifetime på JWT
        options.TokenValidationParameters.ValidateAudience = false; // Ikke validér clients(audience), fx BlazorWeb, der skal anvende IdentityServer
        options.TokenValidationParameters.ValidateIssuer = false; // Ikke validér IdentityServer(issuer)
        options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"])); // Sæt secret key for JWT, der bruges som adgangskode til at tilgå JWT
    });

builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<AuthenticationStateProvider, AppState>();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

RewriteOptions options = new RewriteOptions();
options.AddRedirectToWww();
options.AddRedirectToHttps();
app.UseRewriter(options);

app.UseStaticFiles();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

尝试在高级设置的 IIS 应用程序池中将 Load User Profile 设置为 true。 看到这个answer,希望对你有帮助!

经过几个小时的研究,我设法修复了它。我做了以下事情;添加了 builder.Services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(@"c:\your\path\to\store\keys"));.