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

脚手架生成Identity后报错:未注册UserManager服务求助

解决"No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[OAS.Model.User]' has been registered"异常

这个问题的核心是自定义Identity用户类后,未在服务配置中正确注册对应的Identity服务。以下是具体解决步骤:

1. 检查并更新服务注册代码

在Program.cs(.NET 6+)或Startup.cs(.NET 5及以下)中,确保Identity服务注册时指定了你的自定义User类:

.NET 6+ 示例(Program.cs)

// 替换默认的IdentityUser为你的自定义User类
builder.Services.AddDefaultIdentity<User>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

.NET 5及以下 示例(Startup.cs)

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
    // 注册Identity时指定自定义User类
    services.AddIdentity<User, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    
    // 其他服务配置...
}

2. 确认DbContext继承正确

确保你的ApplicationDbContext继承自IdentityDbContext<User>,而非默认的IdentityDbContext:

public class ApplicationDbContext : IdentityDbContext<User>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

3. 更新数据库迁移(可选但必要)

由于你扩展了IdentityUser添加了Description字段,需要生成新的迁移并更新数据库:

# 生成迁移
Add-Migration AddUserDescriptionField
# 更新数据库
Update-Database

附:你的代码确认

_LoginPartial.cshtml

@using Microsoft.AspNetCore.Identity
@using OAS.Model

@inject SignInManager<User> SignInManager
@inject UserManager<User> UserManager

<ul class="navbar-nav">
@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
        <a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
    </li>
    <li class="nav-item">
        <form id="logoutForm" class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Page("/Index", new { area = "" })">
            <button id="logout" type="submit" class="nav-link btn btn-link text-dark">Logout</button>
        </form>
    </li>
}
else
{
    <li class="nav-item">
        <a class="nav-link text-dark" id="register" asp-area="Identity" asp-page="/Account/Register">Register</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" id="login" asp-area="Identity" asp-page="/Account/Login">Login</a>
    </li>
}
</ul>

User.cs

public class User : IdentityUser
{
    [Required]
    public string Description { get; set; }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:45:36