我正在尝试在我的Web应用程序中实现身份。我添加了从IdentityUser基类继承的自定义用户。对于角色,我使用基本IdentityRole类。我还使用DbInitializer提供一些种子数据,以防它在数据库中不存在。项目:ASP.NET Core Web APP(Model-View-Controller).NET版本:6
相应的代码片段:
AppDbConetxt
public class AppDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Actor> Actors { get; set; }
public DbSet<Cinema> Cinemas { get; set; }
public DbSet<Movie> Movies { get; set; }
public DbSet<Producer> Producers { get; set; }
//Order related tables
public DbSet<Order> Orders { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
}
字符串
申请用户
public class ApplicationUser : IdentityUser
{
[Display(Name = "Full name")]
public string FullName { get; set; } //This is the additional property which does not come from the IdentityUser class.
}
型
program.cs(* 不提供库 *)
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
//Adding DbContext configurations
builder.Services.AddDbContext<AppDbContext>(options =>
{
//In order to use SQL Server we need to add a new NuGet package Microsoft.EntityFrameworkCore.SqlServer
options.UseSqlServer(builder.Configuration.GetConnectionString("eTicketsConnection"));
});
//Service Registration
builder.Services.AddScoped<IActorsService, ActorsService>();
builder.Services.AddScoped<IProducersService, ProducersService>();
builder.Services.AddScoped<ICinemasService, CinemaService>();
builder.Services.AddScoped<IMoviesService, MoviesService>();
builder.Services.AddScoped<IOrdersService, OrdersService>();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddScoped(sc => ShoppingCart.GetShoppingCart(sc));
builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<AppDbContext>();
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
builder.Services.AddMemoryCache();
builder.Services.AddSession();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
//Authentication & Authrorization
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
//Seed Data
AppDbInitializer.Seed(app);
//Seed User and Roles
AppDbInitializer.SeedUsersAndRoles(app).Wait();
app.Run();
型
AppDbInitializer
public class AppDbInitializer
{
public static async Task SeedUsersAndRoles(IApplicationBuilder applicationBuilder)
{
using (IServiceScope serviceScope = applicationBuilder.ApplicationServices.CreateScope())
{
RoleManager<IdentityRole> roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
if (!await roleManager.RoleExistsAsync(UserRoles.Admin))
await roleManager.CreateAsync(new IdentityRole(UserRoles.Admin));
if(!await roleManager.RoleExistsAsync(UserRoles.User))
await roleManager.CreateAsync(new IdentityRole(UserRoles.User));
UserManager<ApplicationUser> userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string adminUserEmail = "[email protected]";
ApplicationUser adminUser = await userManager.FindByEmailAsync(adminUserEmail);
if(adminUser == null)
{
ApplicationUser newAdminUser = new ApplicationUser()
{
FullName = "Admin User",
UserName = "admin-user",
Email = adminUserEmail,
EmailConfirmed = true
};
await userManager.CreateAsync(newAdminUser, "Coding123"); //Adding to the database
await userManager.AddToRoleAsync(newAdminUser, UserRoles.Admin); //Checks if the user exists in the database and adds the role.
}
string appUserEmail = "[email protected]";
ApplicationUser appUser = await userManager.FindByEmailAsync(appUserEmail);
if (appUser == null)
{
ApplicationUser newAppuser = new ApplicationUser()
{
FullName = "Application User",
UserName = "app-user",
Email = adminUserEmail,
EmailConfirmed = true
};
await userManager.CreateAsync(newAppuser, "Coding123"); //Adding to the database
await userManager.AddToRoleAsync(newAppuser, UserRoles.User); //Checks if the user exists in the database and adds the role.
}
}
}
}
型
这是错误消息
x1c 0d1x的数据
我试着解释我在ASP.NETCoreMVC中遇到的关于身份实现的问题,希望得到解决方案。
1条答案
按热度按时间wsxa1bj11#
在应用程序用户的
AppDbInitializer
中,您可能错误地使用了adminUserEmail
而不是appUserEmail
。这将创建具有相同电子邮件地址的两个用户,如果您尝试通过电子邮件检索他们,可能会导致InvalidOperationException
,因为FindByEmailAsync
期望每个电子邮件地址只有一个用户。字符串