如何在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给出的配置代码:
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

