使用 Identity 内置的 RoleManager 创建角色。

步骤

  1. 创建 CreateRoleViewModel ```csharp using System.ComponentModel.DataAnnotations;

namespace StudentManagement.ViewModels { public class CreateRoleViewModel { [Required] [Display(Name = “角色”)] public string RoleName { get; set; } } }

  1. 2. 创建 AdminController 并完善 CreateRole 方法
  2. ```csharp
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Identity;
  5. using Microsoft.AspNetCore.Mvc;
  6. using StudentManagement.ViewModels;
  7. namespace StudentManagement.Controllers
  8. {
  9. public class AdminController : Controller
  10. {
  11. private readonly RoleManager<IdentityRole> _roleManager;
  12. public AdminController(RoleManager<IdentityRole> roleManager)
  13. {
  14. _roleManager = roleManager;
  15. }
  16. [HttpGet]
  17. public IActionResult CreateRole()
  18. {
  19. return View();
  20. }
  21. [HttpPost]
  22. public async Task<IActionResult> CreateRole(CreateRoleViewModel model)
  23. {
  24. if (ModelState.IsValid)
  25. {
  26. var identityRole = new IdentityRole
  27. {
  28. Name = model.RoleName
  29. };
  30. // 如果尝试创建重名角色,会收到验证错误
  31. IdentityResult result = await _roleManager.CreateAsync(identityRole);
  32. if (result.Succeeded)
  33. {
  34. return RedirectToAction("Index", "Home");
  35. }
  36. foreach (var error in result.Errors)
  37. {
  38. ModelState.AddModelError("", error.Description);
  39. }
  40. }
  41. return View(model);
  42. }
  43. }
  44. }
  1. 创建 CreateRole 视图 ```csharp @model CreateRoleViewModel

@{ ViewBag.Title = “创建角色”; }

```