【问题标题】:No service for type 'Microsoft.AspNetCore.Identity.RoleManager error没有针对类型“Microsoft.AspNetCore.Identity.RoleManager 错误的服务”
【发布时间】:2019-02-06 20:48:50
【问题描述】:

我在 ASP.NET CORE 2.1 应用程序上设置用户角色。但是当我尝试使用 RoleManager 时,它会出错。我得到的错误是:

No service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' has been registered.)'

我查看了整个应用程序以查看 IdentityUser 是否仍然存在,因为我创建了一个继承自它的类 ( ApplicationUser ),但其他一切似乎都是正确的。添加services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); 给出运行时错误说明:NotSupportedException: Store does not implement IUserRoleStore&lt;TUser&gt;. 添加Service.AddDefaultIdentity()而不是AddIdentity()也不起作用。

public class Startup
{

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        //services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ApplicationDBContextConnection")));


        //services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDBContext>();

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = true;
            options.Password.RequireLowercase = false;
            options.Password.RequiredUniqueChars = 6;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;
            options.Lockout.AllowedForNewUsers = true;

            // User settings
            options.User.RequireUniqueEmail = true;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, UserManager<ApplicationUser> userManager)
    {


        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();


        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        CreateUserRoles(userManager).GetAwaiter().GetResult();
    }
    private async Task CreateUserRoles( UserManager<ApplicationUser> userManager)
    {

        var UserManager = userManager;

        //Assign Admin role to the main User here we have given our newly registered 
        //login id for Admin management
        ApplicationUser user = await UserManager.FindByEmailAsync("test@test.com");
        UserManager.AddToRoleAsync(user, "Admin").GetAwaiter().GetResult();
    }
}

【问题讨论】:

  • Identity.AddDefaults() 不能解决我的问题。但是,感谢您的关注!
  • 所以你试过services.AddDefaultIdentity&lt;IdentityUser&gt;().AddRoles&lt;IdentityRole&gt;().AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()
  • 是的,我刚才把它放到我的帖子里了。
  • 请更新 Startup 类代码 sn-p 以反映您的最新更改。

标签: c# asp.net-core


【解决方案1】:

您可以将任何已注册的服务显式注入Configure() 方法。

public void Configure(RoleManager<IdentityRole> roleManager)

我不确定当您尝试注入 IServiceProvider 时发生了什么,但它看起来不正确。

另外,不要使用.Wait(),而是使用.GetAwaiter().GetResult()

【讨论】:

  • 感谢您的解释。遗憾的是,直接注入 rolemanager 和 usermanager 会出现同样的错误。
【解决方案2】:

我想通了。

我创建了一个新的 ApplicationUser 类,它继承自 IdentityUser。之后我运行了 Identity 脚手架,声明使用我的 ApplicationUser 作为新类。

在这样做的同时,.NET CORE 创建了一个额外的类:

    public class IdentityHostingStartup : IHostingStartup
{
    public void Configure(IWebHostBuilder builder)
    {
        builder.ConfigureServices((context, services) => {
            services.AddDbContext<ApplicationDBContext>(options =>
                options.UseSqlServer(
                    context.Configuration.GetConnectionString("ApplicationDBContextConnection")));

            services.AddDefaultIdentity<ApplicationUser>()
                .AddEntityFrameworkStores<ApplicationDBContext>();
        });
    }
}

此类中的配置会覆盖启动类中的每个选项和服务(已声明)。如果您在两个类中声明了相同的选项/服务,它将崩溃。这就是它不起作用的原因。将.AddRoles&lt;IdentityRole&gt;() 添加到 IdentityHostingStartUp 后,一切正常!

我仍在寻找一种方法来删除 IdentityHostingStartUp,只是删除那些声明的内容会让应用程序崩溃。

【讨论】:

    【解决方案3】:

    如果您在 .NET 5 中使用 IdentityServer4 或 Duende.IdentityServer Startup.cs。查找以下值:

    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    将其编辑为如下所示:

    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    【讨论】:

      猜你喜欢
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      相关资源
      最近更新 更多