ASP.NET Core 2.2创建IdentityUser [英] ASP.NET Core 2.2 Create IdentityUser

查看:116
本文介绍了ASP.NET Core 2.2创建IdentityUser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.Net Core的全新功能.必须使用Identity创建一个asp.net core 2.2项目(并为用户播种).

Brand new to ASP.Net Core. Having to create an asp.net core 2.2 project with Identity (and have users seeded).

我找不到有关如何执行此操作的任何文档.

I can't find any documentation on how to do this exactly.

我能够找到创建身份角色的代码(无论如何都可以编译,还没到我可以运行它的地方:

I was able to find the code to create Identity Roles (compiles anyway, haven't gotten to where I can run it yet:

  private static async Task CreateUserTypes(ApplicationDbContext authContext, IServiceProvider serviceProvider)
  {
     var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
     string[] roleNames = { "Administrator", "Data Manager", "Interviewer", "Respondent" };
     IdentityResult roleResult;
     foreach (var roleName in roleNames)
     {
        var roleExist = await RoleManager.RoleExistsAsync(roleName);
        if (!roleExist)
        {
           roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
        }
     }
  }

现在,我需要创建一些用户.但是我无法找到带有奇怪的Microsoft语法的代码(谷歌搜索了2天).

Now, I need to create some users. But the with the weird microsoft syntax to do that I can't find (been googling for 2 days).

这是无效的作用:

   private static async Task CreateRootUser(Models.CensORContext context, ApplicationDbContext authContext, IServiceProvider serviceProvider)
  {
     //Create the root ADMIN user for all things admin.
     UserManager<ApplicationDbContext> userManager = serviceProvider.GetRequiredService<UserManager<ApplicationDbContext>>();

     IdentityUser user = new IdentityUser()
     {
        UserName = "admin@admin.admin",
        Email = "admin@admin.admin"
     };

     var NewAdmin = await userManager.CreateAsync(user, "password");
  }

我看到的错误是:

参数1:无法从"Microsoft.AspNetCore.Identity.IdentityUser"转换为"ApplicationDbContext"

Argument1: cannot convert from 'Microsoft.AspNetCore.Identity.IdentityUser' to 'ApplicationDbContext'

那是什么意思?显然,我没有正确的userManager.但是,如何获取正确的参数,该参数将用户作为第一个参数,并将用户名作为第二个字符串(密码)?

Does that mean? Obviously, I don't have the right userManager. But, how do I get the right one that takes a user as the 1st parameter and a string (password) for the 2nd?

此外,在Google搜索中出现的示例中有一个我没有(也不需要?)的 ApplicationUser 对象.在示例中未定义如何获得它.

In addition, the examples that come up in Google searches have an ApplicationUser object that I do not have (and don't need?). Not defined in the examples as to how I get it.

欧文

好.遇到语法错误,但是现在我遇到了运行时错误:

OK. Got past syntax error, but now I'm getting a runtime error:

NullReferenceException:对象引用未设置为对象的实例.在对CreateAsync的调用上.这是新代码:

NullReferenceException: Object reference not set to an instance of an object. on the call to CreateAsync. Here's the new code:

private static async Task CreateRootUser(Models.CensORContext context, ApplicationDbContext authContext, IServiceProvider serviceProvider)
{
     //Create the root ADMIN user for all things admin.         
     var userStore = new UserStore<IdentityUser>(authContext);
     UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(userStore, null, null, null, null, null, null, serviceProvider, null);
     // = serviceProvider.GetRequiredService<UserManager<ApplicationDbContext>>();

     IdentityUser user = new IdentityUser()
     {
        UserName = "admin@admin.admin",
        Email = "admin@admin.admin"
     };

     var result = await userManager.CreateAsync(user, "password");
}

要研究创建userManager的其他参数是什么,以及如何从serviceProvider中获取它们?

Going to be looking into what the other parameters are to the create userManager and how to get them from the serviceProvider?

-欧文

弄清楚怎么做.关键是找到正确的服务提供商以传递正确的语法来创建userManager.我在Google上找到的其他答案全部IdentityUser替换为自己的ApplicationUser ,这使水变得浑浊.这是工作功能(希望这对某人有帮助):

Figured out how to do it. The key was finding the correct serviceprovider to pass in and the right syntax for creating the userManager. The other answers I've found through google all replace the IdentityUser with their own ApplicationUser that was muddying the water. Here's the working function (hope this helps someone):

  private static async Task CreateRootUser(Models.CensORContext context, ApplicationDbContext authContext, IServiceProvider serviceProvider)
  {
     //Create the root ADMIN user for all things admin.         
     var userStore = new UserStore<IdentityUser>(authContext);
     UserManager<IdentityUser> userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
     //new UserManager<IdentityUser>(userStore, null, null, null, null, null, null, serviceProvider, null);
     // = serviceProvider.GetRequiredService<UserManager<ApplicationDbContext>>();

     IdentityUser user = new IdentityUser()
     {
        UserName = "admin@admin.admin",
        Email = "admin@admin.admin"
     };

     var result = await userManager.CreateAsync(user, "password");
     result = await userManager.AddToRoleAsync(user, "Administrator");
  }

推荐答案

您的主要问题似乎是依赖注入.看看此链接有关更多信息.只要您以正确的方式注入DbContextUserManager,其余代码就可以了.

Your main issue seems to be dependency injection. Have a look at this link for more information. As long as you inject your DbContext and UserManager in the right way and the rest of the code should be fine.

这里是一个例子.您可以为种子设置单独的服务,以确保将代码与其余代码分离.

Here is an example. You can set up a separate service for seeding to ensure you decouple your code from the rest.

public class UserSeeder
{
    private readonly UserManager<IdentityUser> userManager;
    private readonly ApplicationDbContext context;

    public UserSeeder(UserManager<IdentityUser> userManager, ApplicationDbContext context)
    {
        this.userManager = userManager;
        this.context = context;
    }

    public async Task `()
    {
        string username = "admin@admin.admin";
        var users = context.Users;
        if (!context.Users.Any(u => u.UserName == username))
        {
            var done = await userManager.CreateAsync(new IdentityUser
            {
                UserName = username,
                Email = username
            }, username);
        }
    }

}

然后,您必须在启动时使用services.AddScoped<UserSeeder>()将此类添加为作用域(因为您的DbContext受作用域).现在,您可以简单地将UserSeeder注入任何服务(单例除外)并调用UserSeeder函数.例如,您可以在主控制器中注入UserSeeder并将其称为index动作.这样可以检查种子并在最初添加种子.但是,仅当您首先进入主页时,此方法才有效.另外,您可以在启动类中设置这样的中间件:

You then have to add this class as a scoped (since your DbContext is scoped) by using services.AddScoped<UserSeeder>() in your startup. You can now simply inject your UserSeeder in any service (except singletons) and call your UserSeeder function. For instance, You can inject UserSeeder in the home controller and call it index action. This way the seeding is checked and added initially. However, this will only work IF you go to the home page first. Alternatively, you can set up a middleware like this in your startup class:

app.Use(async (context, next) => {
    await context.RequestServices.GetService<UserSeeder>().SeedAsync();
    await next();
});

请注意,这两种方式都是您每次都在调用数据库.您可以计划将其放置在何处.您还可以确保仅在布尔值的帮助下(仅在单例中)调用一次.但是请注意,这只能在应用程序启动时运行.

Note that both of these ways, you are calling the database every time. You can plan on where to place it. You can also make sure this is only called once with the help of a boolean (could be in a singleton). But note that this would only run on application startup.

这篇关于ASP.NET Core 2.2创建IdentityUser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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