c# - AddEntityFrameworkStores 只能由派生自 IdentityUser<TKey> 的用户调用

标签 c# asp.net entity-framework entity-framework-core asp.net-2.0

我正在尝试为我的 Web 应用程序创建一些角色,但由于 Tkey 异常,它并没有真正工作。

如果您投赞成票,我很高兴,这样其他需要帮助的人就可以更多地看到它。

我不知道如何解决它。我认为我的 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>();

关于c# - AddEntityFrameworkStores 只能由派生自 IdentityUser<TKey> 的用户调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58387791/

相关文章:

c# - 重复使用套接字还是每次都创建一个新套接字?

c# - HttpClient postasync 与正文 C# 的自定义 header 和 application/json

c# - 复杂类型 : multiple instances in one model?

c# - 将新项目添加到导航属性会导致 "Collection navigation properties must > implement ICollection<> of the target type"错误

c# - 这种 await/async 的用法是否正确?

c# - 在 C# WPF 窗体中运行 javascript

c# - 如何默认生成类型为 'Text' 而不是 'General' 的 Excel 文件

asp.net - 为什么 DotNetNuke 禁用了验证?

ASP.NET 4 SQL 方法?

entity-framework - 如何为多对多关系表指定模式?