在我的网站中,我想让管理员使用帐户登录以修改数据库。此外,我可能会在将来添加一些角色和帐户。
因此,我正在尝试实现标识。
我在Visual Studio 2019中做了一个项目(不确定这是否重要),并使用MVC选择了 ASP.NET Core 2.2(我自己安装了Core 2.2),使用个人用户帐户进行身份验证,我点击了显示:“配置HTTPS”的框。
完成项目后,我打开它,创建一个随机帐户,得到一个错误,然后迁移数据库以修复它。
然后,我添加:appsetting.json
"UserSettings": {
"UserName": "MyAdminUser",
"UserEmail": "MyAdminUser@gmail.com",
"UserPassword": "A_123456a"
}
在文件夹内创建一个新类:Data
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WebApplication1.Data {
public static class Seed {
public static async Task CreateRoles(IServiceProvider serviceProvider, IConfiguration Configuration) {
// Add customs roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
// Note: I used IdentityUser instead of make my ApplicationUser as other people do because the default idendity is fine for me, I don't need additional fields nor I want to make this more difficult.
var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
string[] roleNames = { "Admin" };
IdentityResult roleResult;
foreach (var roleName in roleNames) {
// Create roles and seeding them to the database
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist) {
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
// Create a super user
var poweruser = new IdentityUser {
UserName = Configuration.GetSection("AppSettings")["UserSettings:UserName"],
Email = Configuration.GetSection("AppSettings")["UserSettings:UserEmail"]
};
}
呼如林
一只萌萌小番薯
相关分类