asp.net 只能使用从IdentityUser派生的用户调用AddIdentityFrameworkStores< TKey>

hrysbysz  于 2023-10-21  发布在  .NET
关注(0)|答案(3)|浏览(129)

我试图为我的web应用程序创建一些角色,但由于Tkey exception,它无法真正工作。
我很高兴你给予一个赞成票,这样其他需要帮助的人就可以更多地看到它。
我不知道该怎么补救。我想我的Startup.cs有问题。
无论我尝试添加DefaultIdentity和添加角色。

Startup.cs -在这一行我得到一个错误:

services.AddDefaultIdentity<IdentityRole>().AddRoles<IdentityRole>().AddDefaultUI().AddEntityFrameworkStores<VerwaltungsprogrammContext>();

这是错误消息:> AddIdentityFrameworkStores只能通过从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();
    }
}

}

错误:

只能使用从IdentityUser派生的用户调用AddIdentityFrameworkStores
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");
            }
        }
    }
}
}
k4ymrczo

k4ymrczo1#

如果你在Startup.cs中这样写这一行,也会发生错误吗?

services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<VerwaltungsprogrammContext>();
bprjcwpo

bprjcwpo2#

我认为问题可能与你的身份用户类,所以也许你忘了添加身份用户到你的AppUser类,你可以检查它。

public class AppUser : IdentityUser   <-
{
  //Some properties
}

有时任何人都可能忘记这一点,因此对于遇到此问题的每个人,请确保将IdentityUser添加到您的身份类中。

d5vmydt9

d5vmydt93#

我通过再次创建项目并切换到用户帐户身份验证来修复它,对于每个有同样问题的人,我建议这样做。

相关问题