【问题标题】:IdentityServer4 and ASP.NET Core 2.2 Integrating with ASP.NET IdentityIdentityServer4 和 ASP.NET Core 2.2 与 ASP.NET Identity 集成
【发布时间】:2026-01-13 22:25:02
【问题描述】:

收到此错误

InvalidOperationException:没有注册类型“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”的服务。

我正在尝试将 identityserver 和 asp.net 身份 ui 放在一个项目中。

关注此http://docs.identityserver.io/en/dev/quickstarts/6_aspnet_identity.html#new-project-for-asp-net-identity 文章以获取所需的额外代码。 我做了以下步骤

  1. 创建 ASP.NET Core 2.2 MVC 应用,单帐户身份验证

  2. 对其进行了测试以确保它可以正常工作,注册用户,登录,一切正常。

  3. 添加了 nuget 包IdentityServer4.AspnetIdentity

  4. 在下方添加了 Config.cs 文件

    public static class Config
    {
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResources.Email(),
        };
    }
    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("eventsapi", "Events Api")
        };
    }
    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "client",
    
                // no interactive user, use the clientid/secret for authentication
                AllowedGrantTypes = GrantTypes.ClientCredentials,
    
                // secret for authentication
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
    
                // scopes that client has access to
                AllowedScopes = { "eventsapi" }
            }
        };
    }
    }
    
  5. 添加了 ApplicationUser.cs

    public class ApplicationUser:IdentityUser
    {
    }
    
  6. 修改Startup.cs(注释代码是生成的)

      public class Startup
       {
         public Startup(IConfiguration configuration)
       {
          Configuration = configuration;
       }
    
    public IConfiguration Configuration { get; }
    
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
    
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
    
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        /*
        services.AddDefaultIdentity<IdentityUser>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();
        */
        //REPLACED ABOVE
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
    
    
    
    
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
        //ADDDED
        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity<ApplicationUser>();
    
    }
    
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
             app.UseHsts();
        }
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
    
        //app.UseAuthentication();
        //REPLACED ABOVE
        app.UseIdentityServer();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    

    }

【问题讨论】:

  • 您将在项目中的某处(在控制器或视图中)拥有此代码:UserManager&lt;IdentityUser&gt; userManager。找到所有这些并将它们更改为UserManager&lt;ApplicationUser&gt; userManager

标签: c# asp.net-core identityserver4


【解决方案1】:

对于此错误,请尝试将IdentityUser 更改为Views\Shared\_LoginPartial.cshtml

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

<ul class="navbar-nav">
@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
        <a  class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name!</a>
    </li>
    <li class="nav-item">
        <form  class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
            <button  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" asp-area="Identity" asp-page="/Account/Register">Register</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
    </li>
}
</ul>

然后,您需要注册AddDefaultUI,用于处理对Startup.cs中的action的身份区域请求喜欢

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

【讨论】: