You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署到远程服务器调用PayPal API时出现500错误求助

问题

使用.NET 9构建ASP.NET Core Blazor Web应用,已安装PayPalServerSDK NuGet包。本地Visual Studio 2022通过IIS Express运行时,Javascript调用ApiController完全正常,沙箱和生产环境的PayPal功能均能正常工作。但部署到远程服务器后,点击PayPal按钮返回内部服务器错误500,代码从未进入ApiController,错误在进入控制器前就已触发。服务器日志显示防伪相关异常:

Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery[7]
An exception was thrown while deserializing the token.

当前Program.cs代码如下:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
                .AddInteractiveServerComponents();

builder.Services.AddControllers();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityUserAccessor>();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");

builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = IdentityConstants.ApplicationScheme;
        options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
    })
    .AddIdentityCookies();

builder.Services.AddAuthorizationBuilder()
    .SetFallbackPolicy(new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .Build());

builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddUserManager<UserManager<ApplicationUser>>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddSignInManager()
    .AddApiEndpoints()
    .AddDefaultTokenProviders();

builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
builder.Services.AddDbContextFactory<PrimaryDbContext>();
builder.Services.AddDbContextFactory<LocalBackupDbContext>();
builder.Services.AddDbContextFactory<RemoteBackupDbContext>();
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddSyncfusionBlazor();
builder.Services.AddSignalR(e => { e.MaximumReceiveMessageSize = 256 * 1024; });
builder.Services.AddBlazorise(options => { options.Immediate = true; });
builder.Services.AddBootstrap5Providers();
builder.Services.AddFontAwesomeIcons();
builder.Services.AddScoped<AppState>();
builder.Services.AddScoped<ClipboardService>();
builder.Services.AddSingleton<ICircuitUserService, CircuitUserService>();
builder.Services.AddScoped<CircuitHandler>((sp) => new CircuitHandlerService(sp.GetRequiredService<ICircuitUserService>()));

var app = builder.Build();

Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("Ngo9BigBOggjHTQxAR8/V1NNaF5cXmBCf1FpRmJGdld5fUVHYVZUTXxaS00DNHVRdkdmWXxcdnVVRGFfU0FwWEZWYUA=");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseAntiforgery();

app.MapStaticAssets();

app.MapIdentityApi<ApplicationUser>();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.MapControllers();
app.MapAdditionalIdentityEndpoints();

app.Run();

请问是Program.cs缺少配置导致的错误吗?还是有其他需要排查的点?


排查与解决方案

一、防伪令牌核心配置问题

  1. 统一数据保护密钥
    远程服务器环境中,ASP.NET Core防伪令牌依赖数据保护系统加密。若服务器为多实例部署,或未配置持久化的DataProtection密钥,会导致令牌序列化/反序列化失败。在Program.cs中添加以下配置,确保本地与远程密钥一致:
builder.Services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo(@"D:\SecureKeys")) // 替换为服务器安全目录
    .SetApplicationName("YourBlazorApp"); // 本地与远程应用名称必须完全一致

注意:生产环境需确保密钥目录仅允许应用进程访问,避免权限泄露。

  1. 显式配置防伪选项
    生产环境默认启用防伪Cookie的Secure属性,若服务器HTTPS配置异常,会导致Cookie无法正确传递。可在Program.cs中显式配置:
builder.Services.AddAntiforgery(options =>
{
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.HeaderName = "X-CSRF-TOKEN"; // 与前端请求携带的Header名称匹配
});

二、前端请求令牌传递检查

确认前端Javascript调用API时,是否正确携带防伪令牌:

  • Blazor Server中,可通过HttpContext.Request.Cookies[AntiforgeryDefaults.CookieName]获取令牌,然后在请求头中添加X-CSRF-TOKEN字段。
  • 避免使用multipart/form-data类型的请求(除非显式处理令牌),否则防伪验证会直接失败。

三、服务器环境排查

  1. 验证.NET 9运行时完整性
    远程服务器需安装与本地一致的.NET 9 Runtime版本,避免因运行时差异导致序列化逻辑异常。
  2. 同步系统时钟
    防伪令牌包含过期时间,若服务器与本地时钟偏差过大,会导致令牌提前失效,触发反序列化异常。
  3. 启用详细日志
    在appsettings.json中添加日志配置,获取反序列化异常的具体内部信息:
"Logging": {
    "LogLevel": {
        "Microsoft.AspNetCore.Antiforgery": "Debug"
    }
}

四、Program.cs配置校验

当前Program.cs的UseAntiforgery()调用位置正确,但需确认:

  • MapControllers()在UseAntiforgery()之后,确保防伪验证覆盖所有API控制器。
  • ApiController未误加[IgnoreAntiforgeryToken]特性(本地正常则此可能性较低)。

内容的提问来源于stack exchange,提问作者BY320fo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 09:22:17