gpt4 book ai didi

c# - 没有类型 'Microsoft.AspNetCore.Identity.RoleManager 错误的服务

转载 作者:行者123 更新时间:2023-11-30 22:56:12 30 4
gpt4 key购买 nike

我正在 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<TUser>.添加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();
}
}

最佳答案

我想通了。

我新建了一个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<IdentityRole>()到 IdentityHostingStartUp 一切正常!

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

关于c# - 没有类型 'Microsoft.AspNetCore.Identity.RoleManager 错误的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54562334/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com