如何在 .net core 3.0 应用程序中使用 sql 将新用户添加到数据库?

How to add new user to database using sql in .net core 3.0 application?

在我的应用程序中,我只想让用户登录而不注册,以禁用我关注的注册 this article

要将新用户添加到数据库中,我使用 sql:

INSERT INTO AspNetUsers
(
[UserName],
[Email],
[EmailConfirmed],
[PasswordHash],
[AccessFailedCount],
[Id],
[PhoneNumberConfirmed],
[TwoFactorEnabled],
[LockoutEnabled]
)VALUES
(
'Uladz',
'test@gmailcom',
'true',
'adm1nPassWorD*_',
'3',
'1',
'false',
'false',
'true'
)

但我对 [PasswordHash] 有疑问,将其作为常规字符串插入毫无意义,必须通过身份对其进行加密。

你能告诉我怎样才能得到它,或者我必须使用其他方法吗?

您可以尝试数据播种来设置用户数据。

1.add 一个名为 MyIdentityDataSeeder

的新 class
 public static class MyIdentityDataSeeder
    {
        public static void SeedData(UserManager<IdentityUser> userManager)
        {
            SeedUsers(userManager); 
        }

        public static void SeedUsers(UserManager<IdentityUser> userManager)
        {
            if (userManager.FindByNameAsync("Uladz").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "Uladz";
                user.Email = "test@gmailcom";
                user.EmailConfirmed = true;
                user.AccessFailedCount = 3;
                user.Id = "1";
                user.PhoneNumberConfirmed = false;
                user.TwoFactorEnabled = false;
                user.LockoutEnabled = true;

                IdentityResult result = userManager.CreateAsync(user, "adm1nPassWorD*_").Result;

            }
        }
    }

2.modify 您的 Configure() 方法签名如下所示

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<IdentityUser> userManager)
    {
        ...
        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();


        MyIdentityDataSeeder.SeedData(userManager);

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
    }

参考:http://www.bipinjoshi.net/articles/5e180dfa-4438-45d8-ac78-c7cc11735791.aspx