我正在ASP.NET CORE 2.1应用程序上设置用户角色。但是,当我尝试使用RoleManager时,它会出错。我得到的错误是:
No service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' has been registered.)'
由于已经创建了一个继承自该类的类(ApplicationUser),因此我检查了整个应用程序,以查看IdentityUser
是否仍在任何地方。添加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();
}
}
答案 0 :(得分:0)
您可以将任何注册的服务显式注入Configure()
方法中。
public void Configure(RoleManager<IdentityRole> roleManager)
我不确定您尝试注入IServiceProvider
时发生了什么,但是看起来并不正确。
此外,请勿使用.Wait()
,而应使用.GetAwaiter().GetResult()
。
答案 1 :(得分:0)
我知道了。
我创建了一个新的ApplicationUser类,该类继承自它的IdentityUser。之后,我运行了身份支架,指出将我的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,只清除其中声明的内容将使应用程序崩溃。