当我在调试模式下运行应用程序时,我的种子方法由于“丢失”服务而失败。错误信息是:
尚未注册类型“Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]”的服务。
有人可以帮我在StartUp.cs课堂上正确注册这项服务吗?谢谢!
public static class RolesConfig
{
public static async Task InitialiseAsync(ApplicationDbContext context, IServiceProvider serviceProvider)
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
string[] roleNames = {"Admin", "Report", "Search"};
foreach (var roleName in roleNames)
{
var roleExist = await roleManager.RoleExistsAsync(roleName);
if (!roleExist)
await roleManager.CreateAsync(new IdentityRole(roleName));
}
}
}
Run Code Online (Sandbox Code Playgroud)
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("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddHttpClient();
services.AddHttpClient<IExceptionServiceClient, ExceptionServiceClient>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Run Code Online (Sandbox Code Playgroud)
我认为您错过了 AddRoleManager 的调用。这是我的类似设置,请尝试:
services.AddIdentity<IdentityUser, IdentityRole>(o => {
o.Password.RequiredLength = 8;
})
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6530 次 |
| 最近记录: |