【问题标题】:Seeding user with int ids fails in Asp.net core MVC6在 Asp.net 核心 MVC6 中为具有 int id 的用户播种失败
【发布时间】:2016-04-24 05:50:58
【问题描述】:

我正在使用身份 3。我想在启动时为管理员用户播种。

我已将字符串 ids 转换为“int”ids,以 github 上的 SwiftCourier 为例。标识 3 在某些方面有所不同,这适用于 SwiftCourier 示例中显示的 id 的“int”设置,与 Identity 2 和“int”id 的设置相比。

我通过在我的用户后面放置“int”来做到这一点:

public class User : IdentityUser<int>{...}

在我的角色之后:

public class Role : IdentityRole<int>

在配置服务的 startup.cs 中我输入了这个:

            services.AddIdentity<User, Role>(options => options.User.AllowedUserNameCharacters = null)
            .AddEntityFrameworkStores<JobsDbContext, int>()
            .AddUserStore<UserStore<User, Role, JobsDbContext, int>>()
            .AddRoleStore<RoleStore<Role, JobsDbContext, int>>()
            .AddDefaultTokenProviders();

然后我用它来播种角色,它适用于整数 id:

public static void EnsureRolesCreated(this IApplicationBuilder app)
    {
        var context = app.ApplicationServices.GetService<JobsDbContext>();
        if (context.AllMigrationsApplied())
        {
            var roleManager = app.ApplicationServices.GetService<RoleManager<Role>>();

            var Roles = new List<Role>();

            Roles.Add(new Role { Name = "Admin", Description = "Users able to access all areas" });
            Roles.Add(new Role { Name = "Technician", Description = "Users able to access just the schedule" });

            foreach (var role in Roles)
            {
                if (!roleManager.RoleExistsAsync(role.Name.ToUpper()).Result)
                {
                    roleManager.CreateAsync(role);
                }
            }
        }
    }

到目前为止一切顺利...我只想从一个管理员用户开始,这就是我失败的地方...

我使用了@Guy 提供的以下 Stackoverflow example

我在 UserStore 中苦苦挣扎:

await new UserStore<User>(context).CreateAsync(userWithRoles.User);

它在“用户”上失败,这是我刚刚重命名的应用程序用户。

我得到的错误是:

The type 'JobsLedger.Models.Identity.User' cannot be used as type parameter 'TUser' in the generic type or method 'UserStore<TUser>'. There is no implicit reference conversion from 'JobsLedger.Models.Identity.User' to 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser<string>'.

似乎在抱怨我认为 id 是“int”这一事实

在这方面,如何使 UserStore 与“int”一起使用?如上所示,它在 Startup.cs 中设置为 int..

如果我必须创建一个与“int”一起使用的自定义“UserStore”..你如何在 Identity 3 中做到这一点?

【问题讨论】:

  • 我举了一个将用户添加到角色的例子,它有帮助吗?如果确实如此,请将答案标记为正确答案
  • 我刚刚做到了。我无法使用 int id 在此处创建用户,更不用说向用户添加角色了..它在用户存储上失败..

标签: asp.net-core asp.net-core-mvc asp.net-identity-3


【解决方案1】:

这可能不是最优雅的解决方案,但这很有效......

我的目标是创建一个管理员用户并添加到管理员角色。我已经做到了这一点,同时避免使用带有整数 ID 的 UserStoreand。

using JobsLedger.DAL;
using JobsLedger.Models.Identity;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Identity;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace JobsLedger.Models.Seeding
{
    public static class SeedAdminUser
    {
        public static async void EnsureAdminUserCreated(this IApplicationBuilder app)
        {
            var context = app.ApplicationServices.GetService<JobsDbContext>();
            if (context.AllMigrationsApplied())
            {
                var userManager = app.ApplicationServices.GetService<UserManager<User>>();
                var roleManager = app.ApplicationServices.GetService<RoleManager<Role>>();

                var user = new User
                {
                    UserName = "Admin",
                    NormalizedUserName = "ADMIN",
                    Email = "Email@email.com",
                    NormalizedEmail = "email@email.com",
                    EmailConfirmed = true,
                    LockoutEnabled = false,
                    SecurityStamp = Guid.NewGuid().ToString()
                };

                var password = new PasswordHasher<User>();
                var hashed = password.HashPassword(user, "password");
                user.PasswordHash = hashed;

                var result = await userManager.CreateAsync(user, user.PasswordHash);

                var AdminUser = await userManager.FindByNameAsync("Admin");

                if (AdminUser != null)
                {
                    if (roleManager.RoleExistsAsync("Admin").Result)
                    {
                        var RoleResult = await userManager.AddToRoleAsync(AdminUser, "Admin");
                    }
                }
            }
        }
    }
}

我还在“app.UseIdentity();”之后将此条目放入 StartUp.cs 类中:

app.EnsureAdminUserCreated();

...Models.Identity 中有“用户”类,这就是为什么它包含在“使用”中。

您还需要添加以下内容才能完成这项工作:

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Identity;
using Microsoft.Extensions.DependencyInjection;
using System;

最后,您需要根据上述问题添加角色..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多