ASP.NET Core 標識:角色管理器沒有服務
我有一個使用 Identity 的 ASP.NET Core 應用程序。它可以工作,但是當我嘗試向數據庫添加自定義角色時,我遇到了問題。
在 Startup
ConfigureServices中,我將 Identity 和角色管理器添加為這樣的範圍服務:services.AddIdentity<Entities.DB.User, IdentityRole<int>() .AddEntityFrameworkStores<MyDBContext, int>(); services.AddScoped<RoleManager<IdentityRole>();並在 Startup 中
Configure註入 RoleManager 並將其傳遞給我的自定義類RolesData:public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, RoleManager<IdentityRole> roleManager ) { app.UseIdentity(); RolesData.SeedRoles(roleManager).Wait(); app.UseMvc();這是
RolesData課程:public static class RolesData { private static readonly string[] roles = new[] { "role1", "role2", "role3" }; public static async Task SeedRoles(RoleManager<IdentityRole> roleManager) { foreach (var role in roles) { if (!await roleManager.RoleExistsAsync(role)) { var create = await roleManager.CreateAsync(new IdentityRole(role)); if (!create.Succeeded) { throw new Exception("Failed to create role"); } } } } }該應用程序建構時沒有錯誤,但是在嘗試訪問它時出現以下錯誤:
嘗試啟動“Microsoft.AspNetCore.Identity.RoleManager”時無法解析“Microsoft.AspNetCore.Identity.IRoleStore`1[Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole]”類型的服務
我究竟做錯了什麼?我的直覺說我將 RoleManager 添加為服務的方式有問題。
PS:我在創建項目時使用“無身份驗證”從頭開始學習身份。
我究竟做錯了什麼?我的直覺說我將 RoleManager 添加為服務的方式有問題。
註冊部分實際上很好,你應該刪除
services.AddScoped<RoleManager<IdentityRole>(),因為角色管理器已經為你添加了services.AddIdentity()。您的問題很可能是由泛型類型不匹配引起的:當您呼叫
services.AddIdentity()with 時IdentityRole<int>,您嘗試使用 解決RoleManager,IdentityRole這相當於IdentityRole<string>(string作為 ASP.NET Core Identity 中的預設鍵類型)。更新您的
Configure方法以獲取RoleManager<IdentityRole<int>參數,它應該可以工作。
我遇到了這個問題
沒有“Microsoft.AspNetCore.Identity.RoleManager”類型的服務
這個頁面是Google上的第一個結果。它沒有回答我的問題,所以我想我會將我的解決方案放在這裡,以供其他可能遇到此問題的人使用。
ASP.NET 核心 2.2
對我來說缺少的行是Startup.cs 文件中的**.AddRoles()**。
services.AddDefaultIdentity<IdentityUser>() .AddRoles<IdentityRole>() .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores<ApplicationDbContext>();希望這可以幫助某人
來源:https ://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 (在底部)