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

如何在ASP.NET Razor页面中配置UserManager依赖注入?

问题背景与初始报错

在ASP.NET Razor页面中,尝试通过依赖注入使用UserManager<IdentityUser>,编写的页面代码如下:

public class SetupModel : PageModel
{
      public SetupModel(UserManager<IdentityUser> userManager)
      {
      }
}

由于Program.cs未做额外配置,运行时抛出异常:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager'

核心问题:如何在Program.cs中配置UserManager以实现依赖注入?


尝试ChatGPT方案后的报错

ChatGPT给出的配置代码:

builder.services.AddScoped<UserManager<IdentityUser>>(); 

执行后出现新错误:

Some services are not able to be constructed....Unable to resolve service for type Microsoft.AspNetCore.Identity.IUserStore

当前Program.cs仅包含Visual Studio生成的Microsoft Identity Platform默认认证代码:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages()
     .AddMicrosoftIdentityUI();

注:已通过@User.Identity?.Name!确认SSO认证生效,现在需要获取用户角色信息。


后续尝试与新异常

按照建议修改后的Program.cs代码(适用于.NET 8 Razor页面+HTTPS+Microsoft Identity Platform):

public static void Main(string[] args) {
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
       .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
       .EnableTokenAcquisitionToCallDownstreamApi()
       .AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
       .AddInMemoryTokenCaches();
    
    builder.Services.AddAuthorization(options => {
        options.FallbackPolicy = options.DefaultPolicy;
    });
    builder.Services.AddRazorPages()
       .AddMicrosoftIdentityUI();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment()) {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapRazorPages();
    app.MapControllers();
    
    app.Run();
}

对应的appsettings.json内容:

{
  // This is for SSO using VS Authentication/Identity Platform
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "obfuscated.com",
    "TenantId": "2dc6507f-***obfuscated***524a1",
    "ClientId": "fbc512fe-***obfuscated****",
    "ClientSecret": "gxU8Q***obfuscated***",
    "CallbackPath": "/signin-oidc"
  },
  "DownstreamApi": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "User.ReadWrite.All"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

当前使用的NuGet包版本:

microsoft.identity.web.ui\1.16.0\
microsoft.aspnetcore.authentication.openidconnect\6.0.24\
microsoft.identity.web\1.16.0\
microsoft.graph\4.43.0\
microsoft.aspnetcore.authentication.jwtbearer\6.0.24\
microsoft.identity.web.microsoftgraph\1.16.0\

修改后抛出异常:

The service collection cannot be modified because it is read-only.


最终解决方案

将所有NuGet包升级到最新版本,并将microsoft.identity.web.microsoftgraph替换为Microsoft.Identity.Web.GraphServiceClient。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:23:17