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

.NET Core 7+Identity Server部署IIS后运行异常求助

.NET Core 7 + Angular 部署后Identity Server身份验证空引用异常

我用Visual Studio 2022创建了一个.NET Core 7 + Angular项目,内置Identity Server身份验证。本地运行完全正常,但部署到托管平台后出现以下异常:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.AspNetCore.ApiAuthorization.IdentityServer.IdentityServerJwtBearerOptionsConfiguration.ResolveAuthorityAndKeysAsync(MessageReceivedContext messageReceivedContext)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

我的appsettings.json配置如下:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=<ip address>,1433;Initial Catalog=<dbName>;User ID=<user>;Password=<password>;Trust Server Certificate=true;"
  },
  "Logging": {
      "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
      }
    },
  "IdentityServer": {
    "Clients": {
      "hehn_solutions": {
        "Profile": "IdentityServerSPA"
      }
    }
  },
"AllowedHosts": "*"
}

更新:我的Program.cs是项目默认生成的未修改版本,代码如下:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

builder.Services.AddAuthentication()
    .AddIdentityServerJwt();

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseDeveloperExceptionPage();

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

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");
app.MapRazorPages();

app.MapFallbackToFile("index.html");

app.Run();

我找不到解决方案,求各位帮忙。


解决方法

  1. 添加Identity Server权威地址配置
    生产环境下必须明确指定Identity Server的访问地址,在appsettings.json的IdentityServer节点中添加Authority字段,值为你的托管平台域名(比如https://your-production-domain.com):

    "IdentityServer": {
      "Authority": "https://your-production-domain.com",
      "Clients": {
        "hehn_solutions": {
          "Profile": "IdentityServerSPA"
        }
      }
    }
    
  2. 修正开发中间件的执行时机
    你把app.UseDeveloperExceptionPage();放在了全局执行逻辑中,生产环境不需要这个中间件,还可能干扰身份验证流程。把这行代码移到开发环境判断块内:

    if (app.Environment.IsDevelopment())
    {
        app.UseMigrationsEndPoint();
        app.UseDeveloperExceptionPage(); // 仅在开发环境启用
    }
    else
    {
        app.UseHsts();
    }
    
  3. 确认数据库迁移完成
    部署后要确保Identity Server相关的数据库迁移已执行。可以本地生成迁移脚本,然后在托管平台的数据库手动执行,避免生产环境自动迁移带来的风险。

  4. 检查HTTPS配置
    Identity Server依赖HTTPS完成令牌的颁发和验证,确认托管平台已配置有效SSL证书,且应用已强制跳转HTTPS。

  5. 同步前后端客户端配置
    检查Angular项目中的auth-config.ts(通常在src/app/auth目录),确保其中的authority和后端配置的Authority一致,clientId和appsettings.json中的hehn_solutions完全匹配。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:55:09