需要演练如何创建用户并以一种形式为其分配角色(ASP.NET Core MVC 3+)
Need walk-through of how to create a user and assign a role to it in one form (ASP.NET Core MVC 3+)
- 使用 ASP.NET 核心 MVC 3.1。
- 使用身份脚手架增加了安全性。
- 按照 eShopOnWeb (https://github.com/dotnet-architecture/eShopOnWeb/blob/master/src/Infrastructure/Identity/AppIdentityDbContextSeed.cs)
中的说明创建默认组
- 能够为数据库做种并创建
3 个组:管理员、经理、用户
3 个用户:管理员、经理、用户
将用户分配到相应的组。
- 我需要有关如何在创建用户或需要编辑用户角色时从用户管理表单(MVC 模式)完成为用户分配角色的说明。另外我需要 MVC 模式而不是像这里这样的 Razor 页面 https://github.com/bhrugen/Uplift/blob/master/Uplift/Areas/Identity/Pages/Account/Register.cshtml.cs
我想我需要创建 ViewModel,其中将包含来自 dbo.AspNetUsers、dbo.AspNetRoles、 的条目dbo.AspNetUserRoles 为此,但不确定我到底需要什么以及如何执行。
- 这是表单所需的功能
这是一个简单的工作演示,您可以参考
型号
public class ApplicationUser: IdentityUser
{
public DateTime BirthDate { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class RegisterVM
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Birth date")]
public DateTime BirthDate { get; set; }
public string City { get; set; }
public string Country { get; set; }
[Display(Name ="Management role")]
public string role { get; set; }
public List<IdentityRole> RoleList { get; set; }
}
DbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
}
注册查看
@model MVC3_1Identity.Models.ViewModels.RegisterVM
<div class="row">
<div class="col-md-4">
<form method="post">
<h4>Create a new account.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BirthDate"></label>
<input asp-for="BirthDate" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="City"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Country"></label>
<input asp-for="Country" class="form-control" />
<span asp-validation-for="Country" class="text-danger"></span>
</div>
<div class="custom-checkbox">
<label asp-for="role"></label>
@for (var i = 0; i < Model.RoleList.Count; i++)
{
<input asp-for="role" type="radio" value="@Model.RoleList[i].Name" />
<label asp-for="@Model.RoleList[i].Name">@Model.RoleList[i].Name</label>
}
<span asp-validation-for="role" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
控制器
public IActionResult Register()
{
var model = new RegisterVM();
model.RoleList = _roleManager.Roles.ToList();
return View(model);
}
[HttpPost]
public async Task<IActionResult> Register(RegisterVM model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
BirthDate=model.BirthDate,
City=model.City,
Country =model.Country,
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_userManager.AddToRoleAsync(user,model.role).Wait();
_logger.LogInformation("User created a new account with password and role.");
// other logic you want
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return View();
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser ,IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
结果:
- 使用 ASP.NET 核心 MVC 3.1。
- 使用身份脚手架增加了安全性。
- 按照 eShopOnWeb (https://github.com/dotnet-architecture/eShopOnWeb/blob/master/src/Infrastructure/Identity/AppIdentityDbContextSeed.cs) 中的说明创建默认组
- 能够为数据库做种并创建
3 个组:管理员、经理、用户
3 个用户:管理员、经理、用户
将用户分配到相应的组。 - 我需要有关如何在创建用户或需要编辑用户角色时从用户管理表单(MVC 模式)完成为用户分配角色的说明。另外我需要 MVC 模式而不是像这里这样的 Razor 页面 https://github.com/bhrugen/Uplift/blob/master/Uplift/Areas/Identity/Pages/Account/Register.cshtml.cs
我想我需要创建 ViewModel,其中将包含来自 dbo.AspNetUsers、dbo.AspNetRoles、 的条目dbo.AspNetUserRoles 为此,但不确定我到底需要什么以及如何执行。 - 这是表单所需的功能
这是一个简单的工作演示,您可以参考
型号
public class ApplicationUser: IdentityUser
{
public DateTime BirthDate { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class RegisterVM
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Birth date")]
public DateTime BirthDate { get; set; }
public string City { get; set; }
public string Country { get; set; }
[Display(Name ="Management role")]
public string role { get; set; }
public List<IdentityRole> RoleList { get; set; }
}
DbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
}
注册查看
@model MVC3_1Identity.Models.ViewModels.RegisterVM
<div class="row">
<div class="col-md-4">
<form method="post">
<h4>Create a new account.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BirthDate"></label>
<input asp-for="BirthDate" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="City"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Country"></label>
<input asp-for="Country" class="form-control" />
<span asp-validation-for="Country" class="text-danger"></span>
</div>
<div class="custom-checkbox">
<label asp-for="role"></label>
@for (var i = 0; i < Model.RoleList.Count; i++)
{
<input asp-for="role" type="radio" value="@Model.RoleList[i].Name" />
<label asp-for="@Model.RoleList[i].Name">@Model.RoleList[i].Name</label>
}
<span asp-validation-for="role" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
控制器
public IActionResult Register()
{
var model = new RegisterVM();
model.RoleList = _roleManager.Roles.ToList();
return View(model);
}
[HttpPost]
public async Task<IActionResult> Register(RegisterVM model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
BirthDate=model.BirthDate,
City=model.City,
Country =model.Country,
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_userManager.AddToRoleAsync(user,model.role).Wait();
_logger.LogInformation("User created a new account with password and role.");
// other logic you want
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return View();
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser ,IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
结果: