AddEntityFrameworkStores 只能由派生自 IdentityUser<TKey> 的用户调用
AddEntityFrameworkStores can only be called with a user that derives from IdentityUser<TKey>
我正在尝试为我的 Web 应用程序创建一些角色,但由于 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 can only be called with a user that derives from 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");
}
}
}
}
}
我通过重新创建项目并切换到用户帐户身份验证来修复它,对于遇到同样问题的每个人,我建议这样做。
如果你在你的Startup.cs中这样写行也会出现错误吗?
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<VerwaltungsprogrammContext>();
我正在尝试为我的 Web 应用程序创建一些角色,但由于 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 can only be called with a user that derives from 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");
}
}
}
}
}
我通过重新创建项目并切换到用户帐户身份验证来修复它,对于遇到同样问题的每个人,我建议这样做。
如果你在你的Startup.cs中这样写行也会出现错误吗?
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<VerwaltungsprogrammContext>();