使用Identity时,如何在没有注册页面的情况下注册第一个用户?

您如何在可以管理新数据库的新数据库中创建第一个用户?

例如 Django 有一个命令行实用程序来创建一个超级用户,它是如何在 ASP.Net Identity 中完成的?


江户川乱折腾
浏览 163回答 1
1回答

qq_笑_17

您必须编写自己的种子逻辑来播种默认用户和角色。查看 Jeff Fritz 的CoreWiki 存储库以获取示例。这是相关的部分。请注意如何多次调用它而不必担心创建多个帐户——这很重要,因为每次运行应用程序时都会调用它。public static async Task Seed(UserManager<CoreWikiUser> userManager, RoleManager<IdentityRole> roleManager){&nbsp; &nbsp; var administratorsRole = "Administrator";&nbsp; &nbsp; var defaultAdminUsername = "admin@corewiki.com";&nbsp; &nbsp; var defaultAdminPassword = "Admin@123";&nbsp; &nbsp; var adminRoleExists = await roleManager.RoleExistsAsync(administratorsRole);&nbsp; &nbsp; if (!adminRoleExists)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var role = new IdentityRole(administratorsRole)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = administratorsRole&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; var roleResult = await roleManager.CreateAsync(role);&nbsp; &nbsp; }&nbsp; &nbsp; // If there are no users who are currently an admin, then create a default admin user&nbsp; &nbsp; var anyAdminUsers = await userManager.GetUsersInRoleAsync(administratorsRole);&nbsp; &nbsp; if (!anyAdminUsers.Any())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var defaultAdminUserExists = await userManager.FindByEmailAsync(defaultAdminUsername);&nbsp; &nbsp; &nbsp; &nbsp; if (defaultAdminUserExists == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var defaultAdminUser = new CoreWikiUser&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; UserName = defaultAdminUsername,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Email = defaultAdminUsername&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var userResult = await userManager.CreateAsync(defaultAdminUser, defaultAdminPassword);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (userResult.Succeeded)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var result = await userManager.AddToRoleAsync(defaultAdminUser, administratorsRole);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后,您可以从 Startup 调用它,ConfigureServices()也可以在Main()运行虚拟主机之前直接在您的网络主机中调用它,如果您的种子方法是async.如果传递了命令行参数,另一种方法是在 Main() 中运行它。例如。dotnet run seed.
打开App,查看更多内容
随时随地看视频慕课网APP