新建asp.net core web应用

添加RolesAdminController

  1. [Authorize(Roles = "Admin")]
  2. public class RolesAdminController : Controller
  3. {
  4. private UserManager<ApplicationUser> _userManager;
  5. private RoleManager<IdentityRole> _roleManager;
  6. private readonly ILogger _logger;
  7. public RolesAdminController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, ILogger<AccountController> logger)
  8. {
  9. _userManager = userManager;
  10. _roleManager = roleManager;
  11. _logger = logger;
  12. }
  13.  
  14. //
  15. // GET: /Roles/
  16. public ActionResult Index()
  17. {
  18. return View(_roleManager.Roles);
  19. }
  20.  
  21. //
  22. // GET: /Roles/Details/5
  23. public async Task<ActionResult> Details(string id)
  24. {
  25. if (id == null)
  26. {
  27. throw new ApplicationException();
  28. }
  29. var role = await _roleManager.FindByIdAsync(id);
  30. // Get the list of Users in this Role
  31. var users = new List<ApplicationUser>();
  32.  
  33. // Get the list of Users in this Role
  34. foreach (var user in _userManager.Users.ToList())
  35. {
  36. if (await _userManager.IsInRoleAsync(user, role.Name))
  37. {
  38. users.Add(user);
  39. }
  40. }
  41.  
  42. ViewBag.Users = users;
  43. ViewBag.UserCount = users.Count();
  44. return View(role);
  45. }
  46.  
  47. //
  48. // GET: /Roles/Create
  49. public ActionResult Create()
  50. {
  51. return View();
  52. }
  53.  
  54. //
  55. // POST: /Roles/Create
  56. [HttpPost]
  57. public async Task<ActionResult> Create(IdentityRole roleViewModel)
  58. {
  59. if (ModelState.IsValid)
  60. {
  61. var role = new IdentityRole(roleViewModel.Name);
  62.  
  63. var roleresult = await _roleManager.CreateAsync(role);
  64. if (!roleresult.Succeeded)
  65. {
  66. AddErrors(roleresult);
  67. return View();
  68. }
  69. return RedirectToAction("Index");
  70. }
  71. return View();
  72. }
  73.  
  74. //
  75. // GET: /Roles/Edit/Admin
  76. public async Task<ActionResult> Edit(string id)
  77. {
  78. if (id == null)
  79. {
  80. throw new ApplicationException();
  81. }
  82. var role = await _roleManager.FindByIdAsync(id);
  83. if (role == null)
  84. {
  85. throw new ApplicationException();
  86. }
  87. IdentityRole roleModel = new IdentityRole { Id = role.Id, Name = role.Name };
  88.  
  89. return View(roleModel);
  90. }
  91.  
  92. [HttpPost]
  93. [ValidateAntiForgeryToken]
  94. public async Task<ActionResult> Edit(IdentityRole roleModel)
  95. {
  96. if (ModelState.IsValid)
  97. {
  98. var role = await _roleManager.FindByIdAsync(roleModel.Id);
  99. role.Name = roleModel.Name;
  100.  
  101. await _roleManager.UpdateAsync(role);
  102. return RedirectToAction("Index");
  103. }
  104. return View();
  105. }
  106.  
  107. //
  108. // GET: /Roles/Delete/5
  109. public async Task<ActionResult> Delete(string id)
  110. {
  111. if (id == null)
  112. {
  113. throw new ApplicationException();
  114. }
  115. var role = await _roleManager.FindByIdAsync(id);
  116. if (role == null)
  117. {
  118. throw new ApplicationException();
  119. }
  120. return View(role);
  121. }
  122.  
  123. //
  124. // POST: /Roles/Delete/5
  125. [HttpPost, ActionName("Delete")]
  126. [ValidateAntiForgeryToken]
  127. public async Task<ActionResult> DeleteConfirmed(string id, string deleteUser)
  128. {
  129. if (ModelState.IsValid)
  130. {
  131. if (id == null)
  132. {
  133. throw new ApplicationException();
  134. }
  135. var role = await _roleManager.FindByIdAsync(id);
  136. if (role == null)
  137. {
  138. throw new ApplicationException();
  139. }
  140. IdentityResult result;
  141. if (deleteUser != null)
  142. {
  143. result = await _roleManager.DeleteAsync(role);
  144. }
  145. else
  146. {
  147. result = await _roleManager.DeleteAsync(role);
  148. }
  149. if (!result.Succeeded)
  150. {
  151. AddErrors(result);
  152. return View();
  153. }
  154. return RedirectToAction("Index");
  155. }
  156. return View();
  157. }
  158.  
  159. #region Helpers
  160.  
  161. private void AddErrors(IdentityResult result)
  162. {
  163. foreach (var error in result.Errors)
  164. {
  165. ModelState.AddModelError(string.Empty, error.Description);
  166. }
  167. }
  168.  
  169. private IActionResult RedirectToLocal(string returnUrl)
  170. {
  171. if (Url.IsLocalUrl(returnUrl))
  172. {
  173. return Redirect(returnUrl);
  174. }
  175. else
  176. {
  177. return RedirectToAction(nameof(HomeController.Index), "Home");
  178. }
  179. }
  180.  
  181. #endregion
  182. }

添加对应的View

index

  1. @model IEnumerable<IdentityRole>
  2.  
  3. @{
  4. ViewBag.Title = "Index";
  5. }
  6.  
  7. <h2>Index</h2>
  8.  
  9. <p>
  10. @Html.ActionLink("Create New", "Create")
  11. </p>
  12. <table class="table">
  13. <tr>
  14. <th>
  15. @Html.DisplayNameFor(model => model.Name)
  16. </th>
  17.  
  18. <th>
  19.  
  20. </th>
  21. </tr>
  22.  
  23. @foreach (var item in Model)
  24. {
  25. <tr>
  26. <td>
  27. @Html.DisplayFor(modelItem => item.Name)
  28. </td>
  29.  
  30. <td>
  31. @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
  32. @Html.ActionLink("Details", "Details", new { id = item.Id }) |
  33. @Html.ActionLink("Delete", "Delete", new { id = item.Id })
  34. </td>
  35. </tr>
  36. }
  37.  
  38. </table>

create

  1. @model IdentityRole
  2. @{
  3. ViewBag.Title = "Create";
  4. }
  5. <h2>Create.</h2>
  6. @using (Html.BeginForm())
  7. {
  8. @Html.AntiForgeryToken()
  9.  
  10. <div class="form-horizontal">
  11. <h4>Role.</h4>
  12. <hr />
  13. @Html.ValidationSummary(true)
  14. <div class="form-group">
  15. @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
  16. <div class="col-md-10">
  17. @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
  18. @Html.ValidationMessageFor(model => model.Name)
  19. </div>
  20. </div>
  21.  
  22. <div class="form-group">
  23. <div class="col-md-offset-2 col-md-10">
  24. <input type="submit" value="Create" class="btn btn-default" />
  25. </div>
  26. </div>
  27. </div>
  28. }
  29. <div>
  30. @Html.ActionLink("Back to List", "Index")
  31. </div>
  32. @section Scripts {
  33. @await Html.PartialAsync("_ValidationScriptsPartial")
  34. }

edit

  1. @model IdentityRole
  2. @{
  3. ViewBag.Title = "Edit";
  4. }
  5. <h2>Edit.</h2>
  6. @using (Html.BeginForm())
  7. {
  8. @Html.AntiForgeryToken()
  9.  
  10. <div class="form-horizontal">
  11. <h4>Roles.</h4>
  12. <hr />
  13. @Html.ValidationSummary(true)
  14. @Html.HiddenFor(model => model.Id)
  15. <div class="form-group">
  16. @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
  17. <div class="col-md-10">
  18. @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
  19. @Html.ValidationMessageFor(model => model.Name)
  20. </div>
  21. </div>
  22.  
  23. <div class="form-group">
  24. <div class="col-md-offset-2 col-md-10">
  25. <input type="submit" value="Save" class="btn btn-default" />
  26. </div>
  27. </div>
  28. </div>
  29. }
  30. <div>
  31. @Html.ActionLink("Back to List", "Index")
  32. </div>
  33. @section Scripts {
  34. @await Html.PartialAsync("_ValidationScriptsPartial")
  35. }

details

  1. @model IdentityRole
  2.  
  3. @{
  4. ViewBag.Title = "Details";
  5. }
  6.  
  7. <h2>Role Details.</h2>
  8.  
  9. <div>
  10. <h4>Roles.</h4>
  11. <hr />
  12. <dl class="dl-horizontal">
  13. <dt>
  14. @Html.DisplayNameFor(model => model.Name)
  15. </dt>
  16. <dd>
  17. @Html.DisplayFor(model => model.Name)
  18. </dd>
  19. </dl>
  20.  
  21. </div>
  22. <h4>List of users in this role</h4>
  23. @if (ViewBag.UserCount == )
  24. {
  25. <hr />
  26. <p>No users found in this role.</p>
  27. }
  28.  
  29. <table class="table">
  30.  
  31. @foreach (var item in ViewBag.Users)
  32. {
  33. <tr>
  34. <td>
  35. @item.UserName
  36. </td>
  37. </tr>
  38. }
  39. </table>
  40. <p>
  41. @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
  42. @Html.ActionLink("Back to List", "Index")
  43. </p>

delete

  1. @model IdentityRole
  2.  
  3. @{
  4. ViewBag.Title = "Delete";
  5. }
  6.  
  7. <h2>Delete.</h2>
  8.  
  9. <h3>Are you sure you want to delete this Role? </h3>
  10. <p>Deleting this Role will remove all users from this role. It will not delete the users.</p>
  11. <div>
  12. <h4>Delete Role.</h4>
  13. <hr />
  14. <dl class="dl-horizontal">
  15. <dt>
  16. @Html.DisplayNameFor(model => model.Name)
  17. </dt>
  18.  
  19. <dd>
  20. @Html.DisplayFor(model => model.Name)
  21. </dd>
  22.  
  23. </dl>
  24. @using (Html.BeginForm())
  25. {
  26. @Html.AntiForgeryToken()
  27.  
  28. <div class="form-actions no-color">
  29. <input type="submit" value="Delete" class="btn btn-default" /> |
  30. @Html.ActionLink("Back to List", "Index")
  31. </div>
  32. }
  33. </div>

添加UsersAdminController

  1. [Authorize(Roles = "Admin")]
  2. public class UsersAdminController : Controller
  3. {
  4.  
  5. public UsersAdminController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, ILogger<AccountController> logger)
  6. {
  7. _userManager = userManager;
  8. _roleManager = roleManager;
  9. _logger = logger;
  10. }
  11.  
  12. private UserManager<ApplicationUser> _userManager;
  13. private RoleManager<IdentityRole> _roleManager;
  14. private readonly ILogger _logger;
  15.  
  16. //
  17. // GET: /Users/
  18. public async Task<ActionResult> Index()
  19. {
  20. return View(await _userManager.Users.ToListAsync());
  21. }
  22.  
  23. //
  24. // GET: /Users/Details/5
  25. public async Task<ActionResult> Details(string id)
  26. {
  27. if (id == null)
  28. {
  29. throw new ApplicationException();
  30. }
  31. var user = await _userManager.FindByIdAsync(id);
  32.  
  33. ViewBag.RoleNames = await _userManager.GetRolesAsync(user);
  34.  
  35. return View(user);
  36. }
  37.  
  38. //
  39. // GET: /Users/Create
  40. public async Task<ActionResult> Create()
  41. {
  42. //Get the list of Roles
  43. ViewBag.RoleId = new SelectList(await _roleManager.Roles.ToListAsync(), "Name", "Name");
  44. return View();
  45. }
  46.  
  47. //
  48. // POST: /Users/Create
  49. [HttpPost]
  50. public async Task<ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
  51. {
  52. if (ModelState.IsValid)
  53. {
  54. var user = new ApplicationUser
  55. {
  56. UserName = userViewModel.Email,
  57. Email =
  58. userViewModel.Email,
  59. };
  60.  
  61. // Then create:
  62. var adminresult = await _userManager.CreateAsync(user, userViewModel.Password);
  63.  
  64. //Add User to the selected Roles
  65. if (adminresult.Succeeded)
  66. {
  67. if (selectedRoles != null)
  68. {
  69. var result = await _userManager.AddToRolesAsync(user, selectedRoles);
  70. if (!result.Succeeded)
  71. {
  72. AddErrors(result);
  73. ViewBag.RoleId = new SelectList(await _roleManager.Roles.ToListAsync(), "Name", "Name");
  74. return View();
  75. }
  76. }
  77. }
  78. else
  79. {
  80. AddErrors(adminresult);
  81. ViewBag.RoleId = new SelectList(_roleManager.Roles, "Name", "Name");
  82. return View();
  83.  
  84. }
  85. return RedirectToAction("Index");
  86. }
  87. ViewBag.RoleId = new SelectList(_roleManager.Roles, "Name", "Name");
  88. return View();
  89. }
  90.  
  91. //
  92. // GET: /Users/Edit/1
  93. public async Task<ActionResult> Edit(string id)
  94. {
  95. if (id == null)
  96. {
  97. throw new ApplicationException();
  98. }
  99. var user = await _userManager.FindByIdAsync(id);
  100. if (user == null)
  101. {
  102. throw new ApplicationException();
  103. }
  104.  
  105. var userRoles = await _userManager.GetRolesAsync(user);
  106.  
  107. return View(new EditUserViewModel()
  108. {
  109. Id = user.Id,
  110. Email = user.Email,
  111.  
  112. RolesList = _roleManager.Roles.ToList().Select(x => new SelectListItem()
  113. {
  114. Selected = userRoles.Contains(x.Name),
  115. Text = x.Name,
  116. Value = x.Name
  117. })
  118. });
  119. }
  120.  
  121. //
  122. // POST: /Users/Edit/5
  123. [HttpPost]
  124. [ValidateAntiForgeryToken]
  125. public async Task<ActionResult> Edit(EditUserViewModel editUser, params string[] selectedRole)
  126. {
  127. if (ModelState.IsValid)
  128. {
  129. var user = await _userManager.FindByIdAsync(editUser.Id);
  130. if (user == null)
  131. {
  132. throw new ApplicationException();
  133. }
  134.  
  135. user.UserName = editUser.Email;
  136. user.Email = editUser.Email;
  137.  
  138. var userRoles = await _userManager.GetRolesAsync(user);
  139.  
  140. selectedRole = selectedRole ?? new string[] { };
  141.  
  142. var result = await _userManager.AddToRolesAsync(user, selectedRole.Except(userRoles).ToArray<string>());
  143.  
  144. if (!result.Succeeded)
  145. {
  146. AddErrors(result);
  147. return View();
  148. }
  149. result = await _userManager.RemoveFromRolesAsync(user, userRoles.Except(selectedRole).ToArray<string>());
  150.  
  151. if (!result.Succeeded)
  152. {
  153. AddErrors(result);
  154. return View();
  155. }
  156. return RedirectToAction("Index");
  157. }
  158. ModelState.AddModelError("", "Something failed.");
  159. return View();
  160. }
  161.  
  162. //
  163. // GET: /Users/Delete/5
  164. public async Task<ActionResult> Delete(string id)
  165. {
  166. if (id == null)
  167. {
  168. throw new ApplicationException();
  169. }
  170. var user = await _userManager.FindByIdAsync(id);
  171. if (user == null)
  172. {
  173. throw new ApplicationException();
  174. }
  175. return View(user);
  176. }
  177.  
  178. //
  179. // POST: /Users/Delete/5
  180. [HttpPost, ActionName("Delete")]
  181. [ValidateAntiForgeryToken]
  182. public async Task<ActionResult> DeleteConfirmed(string id)
  183. {
  184. if (ModelState.IsValid)
  185. {
  186. if (id == null)
  187. {
  188. throw new ApplicationException();
  189. }
  190.  
  191. var user = await _userManager.FindByIdAsync(id);
  192. if (user == null)
  193. {
  194. throw new ApplicationException();
  195. }
  196. var result = await _userManager.DeleteAsync(user);
  197. if (!result.Succeeded)
  198. {
  199. AddErrors(result);
  200. return View();
  201. }
  202. return RedirectToAction("Index");
  203. }
  204. return View();
  205. }
  206.  
  207. #region Helpers
  208.  
  209. private void AddErrors(IdentityResult result)
  210. {
  211. foreach (var error in result.Errors)
  212. {
  213. ModelState.AddModelError(string.Empty, error.Description);
  214. }
  215. }
  216.  
  217. private IActionResult RedirectToLocal(string returnUrl)
  218. {
  219. if (Url.IsLocalUrl(returnUrl))
  220. {
  221. return Redirect(returnUrl);
  222. }
  223. else
  224. {
  225. return RedirectToAction(nameof(HomeController.Index), "Home");
  226. }
  227. }
  228.  
  229. #endregion
  230. }

添加对应的EditUserViewModel

  1. public class EditUserViewModel
  2. {
  3. public string Id { get; set; }
  4.  
  5. [Required(AllowEmptyStrings = false)]
  6. [Display(Name = "Email")]
  7. [EmailAddress]
  8. public string Email { get; set; }
  9.  
  10. public IEnumerable<SelectListItem> RolesList { get; set; }
  11. }

添加对应的view

index

  1. @model IEnumerable<WebApplication2.Models.ApplicationUser>
  2.  
  3. @{
  4. ViewBag.Title = "Index";
  5. }
  6.  
  7. <h2>Index</h2>
  8.  
  9. <p>
  10. @Html.ActionLink("Create New", "Create")
  11. </p>
  12. <table class="table">
  13. <tr>
  14. <th>
  15. @Html.DisplayNameFor(model => model.UserName)
  16. </th>
  17.  
  18. <th>
  19.  
  20. </th>
  21. </tr>
  22.  
  23. @foreach (var item in Model)
  24. {
  25. <tr>
  26. <td>
  27. @Html.DisplayFor(modelItem => item.UserName)
  28. </td>
  29.  
  30. <td>
  31. @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
  32. @Html.ActionLink("Details", "Details", new { id = item.Id }) |
  33. @Html.ActionLink("Delete", "Delete", new { id = item.Id })
  34. </td>
  35. </tr>
  36. }
  37.  
  38. </table>

create

  1. @model WebApplication2.Models.AccountViewModels.RegisterViewModel
  2. @{
  3. ViewBag.Title = "Create";
  4. }
  5. <h2>@ViewBag.Title.</h2>
  6. @using (Html.BeginForm("Create", "UsersAdmin", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
  7. {
  8. @Html.AntiForgeryToken()
  9. <h4>Create a new account.</h4>
  10. <hr />
  11. @Html.ValidationSummary("", new { @class = "text-error" })
  12. <div class="form-group">
  13. @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
  14. <div class="col-md-10">
  15. @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
  16. </div>
  17. </div>
  18.  
  19. <div class="form-group">
  20. @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
  21. <div class="col-md-10">
  22. @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
  23. </div>
  24. </div>
  25. <div class="form-group">
  26. @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
  27. <div class="col-md-10">
  28. @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
  29. </div>
  30. </div>
  31. <div class="form-group">
  32. <label class="col-md-2 control-label">
  33. Select User Role
  34. </label>
  35. <div class="col-md-10">
  36. @foreach (var item in (SelectList)ViewBag.RoleId)
  37. {
  38. <input type="checkbox" name="SelectedRoles" value="@item.Value" class="checkbox-inline" />
  39. @Html.Label("Role", item.Value, new { @class = "control-label" })
  40. }
  41. </div>
  42. </div>
  43. <div class="form-group">
  44. <div class="col-md-offset-2 col-md-10">
  45. <input type="submit" class="btn btn-default" value="Create" />
  46. </div>
  47. </div>
  48. }
  49. @section Scripts {
  50. @await Html.PartialAsync("_ValidationScriptsPartial")
  51. }

edit

  1. @model WebApplication2.Models.AdminViewModels.EditUserViewModel
  2. @{
  3. ViewBag.Title = "Edit";
  4. }
  5. <h2>Edit.</h2>
  6.  
  7. @using (Html.BeginForm())
  8. {
  9. @Html.AntiForgeryToken()
  10.  
  11. <div class="form-horizontal">
  12. <h4>Edit User Form.</h4>
  13. <hr />
  14. @Html.ValidationSummary(true)
  15. @Html.HiddenFor(model => model.Id)
  16. <div class="form-group">
  17. @Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })
  18. <div class="col-md-10">
  19. @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
  20. @Html.ValidationMessageFor(model => model.Email)
  21. </div>
  22. </div>
  23.  
  24. <div class="form-group">
  25. @Html.Label("Roles","", new { @class = "control-label col-md-2" })
  26. <span class=" col-md-10">
  27. @foreach (var item in Model.RolesList)
  28. {
  29. <input type="checkbox" name="SelectedRole" value="@item.Value" checked="@item.Selected" class="checkbox-inline" />
  30. @Html.Label("Role",item.Value, new { @class = "control-label" })
  31. }
  32. </span>
  33. </div>
  34. <div class="form-group">
  35. <div class="col-md-offset-2 col-md-10">
  36. <input type="submit" value="Save" class="btn btn-default" />
  37. </div>
  38. </div>
  39. </div>
  40. }
  41. <div>
  42. @Html.ActionLink("Back to List", "Index")
  43. </div>
  44. @section Scripts {
  45. @await Html.PartialAsync("_ValidationScriptsPartial")
  46. }

details

  1. @model WebApplication2.Models.ApplicationUser
  2.  
  3. @{
  4. ViewBag.Title = "Details";
  5. }
  6.  
  7. <h2>Details.</h2>
  8.  
  9. <div>
  10. <h4>User</h4>
  11. <hr />
  12. <dl class="dl-horizontal">
  13. <dt>
  14. @Html.DisplayNameFor(model => model.UserName)
  15. </dt>
  16. <dd>
  17. @Html.DisplayFor(model => model.UserName)
  18. </dd>
  19. </dl>
  20. </div>
  21. <h4>List of roles for this user</h4>
  22. @if (ViewBag.RoleNames.Count == )
  23. {
  24. <hr />
  25. <p>No roles found for this user.</p>
  26. }
  27.  
  28. <table class="table">
  29.  
  30. @foreach (var item in ViewBag.RoleNames)
  31. {
  32. <tr>
  33. <td>
  34. @item
  35. </td>
  36. </tr>
  37. }
  38. </table>
  39. <p>
  40. @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
  41. @Html.ActionLink("Back to List", "Index")
  42. </p>

delete

  1. @model WebApplication2.Models.ApplicationUser
  2.  
  3. @{
  4. ViewBag.Title = "Delete";
  5. }
  6.  
  7. <h2>Delete.</h2>
  8.  
  9. <h3>Are you sure you want to delete this User?</h3>
  10. <div>
  11. <h4>User.</h4>
  12. <hr />
  13. <dl class="dl-horizontal">
  14. <dt>
  15. @Html.DisplayNameFor(model => model.UserName)
  16. </dt>
  17.  
  18. <dd>
  19. @Html.DisplayFor(model => model.UserName)
  20. </dd>
  21. </dl>
  22.  
  23. @using (Html.BeginForm()) {
  24. @Html.AntiForgeryToken()
  25.  
  26. <div class="form-actions no-color">
  27. <input type="submit" value="Delete" class="btn btn-default" /> |
  28. @Html.ActionLink("Back to List", "Index")
  29. </div>
  30. }
  31. </div>

修改共享模板页

Shared/_layout.cshtml

  1. <div class="navbar-collapse collapse">
  2. <ul class="nav navbar-nav">
  3. <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
  4. <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
  5. <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
  6. @if (User!=null && User.IsInRole("Admin"))
  7. {
  8. <li>@Html.ActionLink("RolesAdmin", "Index", "RolesAdmin")</li>
  9. <li>@Html.ActionLink("UsersAdmin", "Index", "UsersAdmin")</li>
  10. }
  11. </ul>
  12. @await Html.PartialAsync("_LoginPartial")
  13. </div>

运行应用,注册两个账号

1@1.com具有Admin角色权限

2@2.com没有 Admin权限

1@1.com可以进入管理页面

2@2.com没有管理页面权限

Role具体实现

UserManager<TUser>类中的IsInRoleAsync(user, role.Name)是个虚方法

  1. public virtual Task<bool> IsInRoleAsync(TUser user, string role);

具体的实现是在Microsoft.AspNet.Identity.EntityFramework 中,使用dotPeek 打开Microsoft.AspNet.Identity.EntityFramework.dll

  1. public virtual async Task<bool> IsInRoleAsync(TUser user, string roleName)
  2. {
  3. this.ThrowIfDisposed();
  4. if ((object) user == null)
  5. throw new ArgumentNullException(nameof (user));
  6. if (string.IsNullOrWhiteSpace(roleName))
  7. throw new ArgumentException(IdentityResources.ValueCannotBeNullOrEmpty, nameof (roleName));
  8. TRole role = (TRole) await (TaskExtensions.CultureAwaiter<TRole>) TaskExtensions.WithCurrentCulture<TRole>(QueryableExtensions.SingleOrDefaultAsync<TRole>((IQueryable<M0>) this._roleStore.DbEntitySet, (Expression<Func<M0, bool>>) (r => r.Name.ToUpper() == roleName.ToUpper())));
  9. if ((object) role == null)
  10. return false;
  11. TKey userId = user.Id;
  12. TKey roleId = role.Id;
  13. ;
  14. }

可以看到判断的依旧是r => r.Name.ToUpper() == roleName.ToUpper()

自定义用户、角色属性

参考:ASP.NET Identity 2.0: Customizing Users and Roles

这里需要修改几处

创建ApplicationRole

  1. public class ApplicationRole:IdentityRole
  2. {
  3. public ApplicationRole() : base() { }
  4. public ApplicationRole(string roleName) : base(roleName) { }
  5. }

修改RolesAdminController和UsersAdminController

将之前的IdentityRole替换成ApplicationRole

修改ApplicationDbContext,加上新建的ApplicationRole及TKey--string

  1. public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole,string>

修改Startup中的ConfigureServices

  1. services.AddIdentity<ApplicationUser, ApplicationRole>()
  2. .AddEntityFrameworkStores<ApplicationDbContext>()
  3. .AddDefaultTokenProviders();

重新运行项目即可

接下来就可以在ApplicationUser和ApplicationRole中添加属性

  1. public class ApplicationRole:IdentityRole
  2. {
  3. public ApplicationRole() : base() { }
  4. public ApplicationRole(string roleName) : base(roleName) { }
  5. public string Description { get; set; }
  6. }

之后更新对应的ViewModel和页面即可。

asp.net core web 添加角色管理的更多相关文章

  1. ASP.NET Core Web API下事件驱动型架构的实现(二):事件处理器中对象生命周期的管理

    在上文中,我介绍了事件驱动型架构的一种简单的实现,并演示了一个完整的事件派发.订阅和处理的流程.这种实现太简单了,百十行代码就展示了一个基本工作原理.然而,要将这样的解决方案运用到实际生产环境,还有很 ...

  2. asp.net core web api + Element-UI的Vue管理后台

    后端:asp.net core web api + EF Core 前端:VUE + Element-UI+ Node环境的后台管理系统. 线上地址:http://www.wangjk.wang/ 密 ...

  3. ASP.NET Core Web API下事件驱动型架构的实现(一):一个简单的实现

    很长一段时间以来,我都在思考如何在ASP.NET Core的框架下,实现一套完整的事件驱动型架构.这个问题看上去有点大,其实主要目标是为了实现一个基于ASP.NET Core的微服务,它能够非常简单地 ...

  4. 使用JWT创建安全的ASP.NET Core Web API

    在本文中,你将学习如何在ASP.NET Core Web API中使用JWT身份验证.我将在编写代码时逐步简化.我们将构建两个终结点,一个用于客户登录,另一个用于获取客户订单.这些api将连接到在本地 ...

  5. Azure 部署 Asp.NET Core Web App

    在云计算大行其道的时代,当你在部署一个网站时,第一选择肯定是各式各样的云端服务.那么究竟使用什么样的云端服务才能够以最快捷的方式部署一个 ASP.NET Core 的网站呢?Azure 的 Web A ...

  6. 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)

    对于开发人员来说,构建一个消费应用程序时去了解各种各样的 API 是一个巨大的挑战.在你的 Web API 项目中使用 Swagger 的 .NET Core 封装 Swashbuckle 可以帮助你 ...

  7. Gitlab CI 自动部署 asp.net core web api 到Docker容器

    为什么要写这个? 在一个系统长大的过程中会经历不断重构升级来满足商业的需求,而一个严谨的商业系统需要高效.稳定.可扩展,有时候还不得不考虑成本的问题.我希望能找到比较完整的开源解决方案来解决持续集成. ...

  8. ASP.NET Core Web 支付功能接入 支付宝-电脑网页支付篇

    这篇文章将介绍ASP.NET Core中使用 开源项目 Payment,实现接入支付宝-电脑网页支付接口及同步跳转及异步通知功能. 开发环境:Win 10 x64.VS2017 15.6.4..NET ...

  9. ASP.NET Core Web 支付功能接入 微信-扫码支付篇

    这篇文章将介绍ASP.NET Core中使用 开源项目 Payment,实现接入微信-扫码支付及异步通知功能. 开发环境:Win 10 x64.VS2017 15.6.4..NET Core SDK ...

随机推荐

  1. windows访问ubuntu的文件

    前提:windows电脑和ubuntu电脑要工作在同一个网段! 1.先要安装Samba sudo apt-get install samba openssh-server 2.编译Samba配置文件 ...

  2. JS、JSP、ASP、CGI

      1)JS是在客户端执行的,需要浏览器支持Javascript.JSP是在服务器端执行的,需要服务器上部署支持Servlet的服务器程序.JS代码是能够直接从服务器上download得到,对外是可见 ...

  3. 深入浅出javascript(八)this、call和apply

    _________此篇日志属于重要记录,长期更新__________ this,call,apply这三个是进阶JS的重要一步,需要详细的记录. ➢ this 一.作为对象的方法调用. 当函数作为对象 ...

  4. sys/time.h 和 time.h

    今天在燕麦工作第二天.看荣哥给我的程序,发现程序里面用的延时跟我以前使用的不同.导入两个头文件,然后用函数来获得时间.关于这个函数特别查来一下. time.h  是ISO C99 标准日期头文件. s ...

  5. python标准库及其它应用

    一: sys模块的介绍: 程序如下: #coding:utf-8import sysprint sys.argv[0]print sys.argv[1]print sys.argv[2] 打开cmd窗 ...

  6. flume遇到的问题

    Caused by: java.lang.IllegalStateException: Unable to add FlumeEventPointer [fileID=, offset=]. Queu ...

  7. 深入理解Aspnet Core之Identity(5)

    主题 本篇我将会介绍验证用户的机制当账户被创建的时候,同样 这个过程主要有IUserValidator这个接口来实现的,和密码验证一样Identity同样也内置已经实现好的账户验证.账户验证的比较简单 ...

  8. CentOS7下让Asp.Net Core的网站自动运行

    一.安装Nginx yum install nginx 二.配置Nginx vi /etc/nginx/nginx.conf location / { proxy_pass http://127.0. ...

  9. C#项目 学生选课系统 C#窗口 Winform项目 项目源码及使用说明

    这是一个学生选课信息管理系统,使用VS2010+SQL2008编写,VS2017正常使用. 项目源码下载地址 https://gitee.com/whuanle/xkgl 笔者录了两个视频,打开项目源 ...

  10. MVC5控制器传值的三种方式(ViewData,ViewBag,TempData),刚刚学习MVC5的新手,希望各位大神多多指教

    mvc传值的三种方式:1.ViewData 在使用过程中需要类型转换 例子: ViewData["MyTitle"]="ViewData传值"; 引用: @Vi ...