身份实施面临多个错误

问题描述 投票:0回答:1

我正在尝试在我的网络应用程序中实现身份。我添加了从 IdentityUser 基类继承的自定义用户。对于角色,我使用 IdentityRole 基类。我还有 DbInitializer 来提供一些种子数据,以防数据库中不存在它。 项目:ASP.NET Core Web APP(模型-视图-控制器) .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();

AppDb初始化器

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.
             }
         }
     }
 }

这是错误信息

screenshot of error message in Visual Studio

我试图解释我所面临的有关 ASP.NET Core MVC 中身份实现的问题。期待得到如何处理问题的解决方案。

c# asp.net .net asp.net-mvc asp.net-identity
1个回答
0
投票

在应用程序用户的

AppDbInitializer
中,您可能错误地使用了
adminUserEmail
而不是
appUserEmail
。这将创建两个具有相同电子邮件地址的用户,如果您尝试通过电子邮件检索它们,可能会导致
InvalidOperationException
,因为
FindByEmailAsync
预计每个电子邮件地址只有一个用户。

string adminUserEmail = "[email protected]";

// ...

string appUserEmail = "[email protected]";

// ...

ApplicationUser newAppuser = new ApplicationUser()
{
    FullName = "Application User",
    UserName = "app-user",
    Email = adminUserEmail, // <-- Maybe it is a copy-paste error. Maybe use it appUserEmail instead adminUserEmail.
    EmailConfirmed = true
};
© www.soinside.com 2019 - 2024. All rights reserved.