Я пытаюсь создать некоторые роли для моего веб-приложения, но оно не работает из-за Tkey exception
.
Я не знаю, как я могу это исправить. Я думаю, что есть проблема с моим Startup.cs.
Что бы я ни пытался добавить DefaultIdentity
и добавить роли.
Startup.cs - В этой строке я получаю сообщение об ошибке:
services.AddDefaultIdentity<IdentityRole>().AddRoles<IdentityRole>().AddDefaultUI().AddEntityFrameworkStores<VerwaltungsprogrammContext>();
Это сообщение об ошибке:
AddEntityFrameworkStores может быть вызван только с пользователем, который является производным от IdentityUser
namespace Verwaltungsprogramm
{
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.AddSession();
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<VerwaltungsprogrammContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("VerwaltungsprogrammContext")));
//services.AddDefaultIdentity<IdentityUser>();
--------------> services.AddDefaultIdentity<IdentityRole>().AddRoles<IdentityRole>().AddDefaultUI().AddEntityFrameworkStores<VerwaltungsprogrammContext>(); <--------------
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
options.Conventions.AuthorizeAreaFolder("Logins", "/Create");
options.Conventions.AuthorizeAreaPage("Logins", "/Logout");
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Logins/Index";
options.LogoutPath = $"/Logins/Logout";
options.AccessDeniedPath = $"/Cars/Index";
});
//Password Strength Setting
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.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});
//Seting the Account Login page
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = "/Logins/Create"; // If the LoginPath is not set here, ASP.NET Core
will default to /Account/Login
options.AccessDeniedPath = "/Cars/Index"; // If the AccessDeniedPath is not set here,
ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
});
services.AddSingleton<IEmailSender, EmailSender>();
}
public class EmailSender : IEmailSender
{
public Task SendEmailAsync(string email, string subject, string message)
{
return Task.CompletedTask;
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Seed.CreateRoles(serviceProvider, Configuration).Wait();
}
}
}
Ошибка:
AddEntityFrameworkStores можно вызывать только с пользователем, который является производным от IdentityUser
Файл Seed.cs
предназначен для создания некоторых ролей
Вот мой Seed.cs
namespace Verwaltungsprogramm
{
public static class Seed
{
public static async Task CreateRoles(IServiceProvider serviceProvider, IConfiguration Configuration)
{
//adding customs roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Manager", "Member" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
// creating the roles and seeding them to the database
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
// creating a super user who could maintain the web app
var poweruser = new ApplicationUser
{
UserName = Configuration.GetSection("AppSettings")["UserEmail"],
Email = Configuration.GetSection("AppSettings")["UserEmail"]
};
string userPassword = Configuration.GetSection("AppSettings")["UserPassword"];
var user = await UserManager.FindByEmailAsync(Configuration.GetSection("AppSettings")["UserEmail"]);
if (user == null)
{
var createPowerUser = await UserManager.CreateAsync(poweruser, userPassword);
if (createPowerUser.Succeeded)
{
// here we assign the new user the "Admin" role
await UserManager.AddToRoleAsync(poweruser, "Admin");
}
}
}
}
}