只能使用从IdentityUser< TKey>派生的用户来调用AddEntityFrameworkStores. [英] AddEntityFrameworkStores can only be called with a user that derives from IdentityUser<TKey>

查看:115
本文介绍了只能使用从IdentityUser< TKey>派生的用户来调用AddEntityFrameworkStores.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的Web应用程序创建一些角色,但是由于Tkey exception,它实际上无法正常工作.

I'm trying to create some roles for my web application but it isn't really working because of a Tkey exception.

我不知道该如何解决.我认为我的Startup.cs有问题.

I don't know how I can fix it. I think there is a problem with my Startup.cs.

无论我尝试添加DefaultIdentity还是添加角色.

Whatever i try to add the DefaultIdentity and adding the roles.

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

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

这是错误消息:

AddEntityFrameworkstores只能与从IdentityUser派生的用户一起调用

AddEntityFrameworkStores can only be called with a user that derives from 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只能与从IdentityUser派生的用户

AddEntityFrameworkStores can only be called with a user that derives from IdentityUser

Seed.cs文件用于创建一些角色

The Seed.cs file is to create some roles

这是我的Seed.cs

Here is my 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中编写该行,是否还会发生错误?

Does the error also occur if you write the line in your Startup.cs like this?

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

这篇关于只能使用从IdentityUser&lt; TKey&gt;派生的用户来调用AddEntityFrameworkStores.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆