使用 Identity 内置的 RoleManager 创建角色。
步骤
- 创建 CreateRoleViewModel ```csharp using System.ComponentModel.DataAnnotations;
namespace StudentManagement.ViewModels { public class CreateRoleViewModel { [Required] [Display(Name = “角色”)] public string RoleName { get; set; } } }
2. 创建 AdminController 并完善 CreateRole 方法```csharpusing System.Threading.Tasks;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;using StudentManagement.ViewModels;namespace StudentManagement.Controllers{public class AdminController : Controller{private readonly RoleManager<IdentityRole> _roleManager;public AdminController(RoleManager<IdentityRole> roleManager){_roleManager = roleManager;}[HttpGet]public IActionResult CreateRole(){return View();}[HttpPost]public async Task<IActionResult> CreateRole(CreateRoleViewModel model){if (ModelState.IsValid){var identityRole = new IdentityRole{Name = model.RoleName};// 如果尝试创建重名角色,会收到验证错误IdentityResult result = await _roleManager.CreateAsync(identityRole);if (result.Succeeded){return RedirectToAction("Index", "Home");}foreach (var error in result.Errors){ModelState.AddModelError("", error.Description);}}return View(model);}}}
- 创建 CreateRole 视图 ```csharp @model CreateRoleViewModel
@{ ViewBag.Title = “创建角色”; }
```