首页 > 解决方案 > InvalidOperationException: No service for type Microsoft.AspNetCore.Identity.UserManager has been registered error using ASP.NET Identity Server

问题描述

我正在尝试将我的所有数据放在一个数据库中,包括业务数据和身份数据。所以,我已经在我的数据库上运行了迁移并更新了我的 DbContext。

我正在尝试从 Blazor Web Assembly 中指定用户的新项目模板修改我的项目。

我运行应用程序。它加载主页。但是,当我单击登录时,我收到错误:

处理请求时发生未处理的异常。InvalidOperationException:没有注册类型“Microsoft.AspNetCore.Identity.UserManager`1[MyProject.Server.Models.ApplicationUser]”的服务。

在我的 MyProject.Server Startup.cs 文件中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddDatabaseDeveloperPageExceptionFilter();

    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
        .AddRoles<IdentityRole>()
        .AddDefaultTokenProviders()
        .AddUserManager<UserManager<ApplicationUser>>()
        .AddSignInManager<SignInManager<ApplicationUser>>()
        .AddEntityFrameworkStores<MyContext>();

    services.AddIdentityServer(
        options =>
        {
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseSuccessEvents = true;
        }
    )
    .AddClientStore<ClientStore>()
    .AddConfigurationStore<MyContext>(options =>
    {
        options.ConfigureDbContext = b => b.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    })
    .AddOperationalStore<MyContext>(options =>
    {
        options.ConfigureDbContext = b => b.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    })
    .AddApiAuthorization<ApplicationUser, MyContext>();

    services.AddAuthentication().AddIdentityServerJwt();

    services.AddControllersWithViews();
    services.AddRazorPages();
}

我的 ApplicationUser 类没有什么特别之处:

public class ApplicationUser : IdentityUser
{
}

在我的 _LoginPartial.cshtml 中:

@using Microsoft.AspNetCore.Identity
@using MyProject.Server.Models
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

我不认为我在尝试做任何特别的事情。主要的是我正在使用覆盖 OnModelCreating 的客户 DbContext。这就是为什么我需要定义这么多 IdentityServer。

标签: asp.net-coreasp.net-identityblazor-webassembly

解决方案


如果您使用的是 .Net core 5,请添加:

services.AddIdentityCore<ApplicationUser>();

根据这里的源代码,这将注册UserManager<ApplicationUser>


推荐阅读