添加角色属性查看

Views ->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.   <li><a asp-area="" asp-controller="Account" asp-action="Index">Account</a></li>
  7.   <li><a asp-area="" asp-controller="Claims" asp-action="Index">Claims</a></li>
  8.   <li><a asp-area="" asp-controller="Role" asp-action="Index">Role</a></li> //加这句

Controllers ->RoleController.cs 新建

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore.Mvc;
  7. using IdentityMvc.Models;
  8. using Microsoft.AspNetCore.Identity;
  9. using Microsoft.AspNetCore.Authorization;
  10. using IdentityMvc.Models.AccountViewModels;
  11. using Microsoft.AspNetCore.Authentication;
  12. using System.ComponentModel.DataAnnotations;
  13. using Microsoft.EntityFrameworkCore;
  14. using IdentityMvc.Models.RoleViewModels;
  15. using System.Security.Claims;
  16.  
  17. namespace IdentityMvc.Controllers
  18. {
  19. [Authorize]
  20. public class RoleController : Controller
  21. {
  22. private readonly UserManager<ApplicationUser> _userManager;
  23. private readonly RoleManager<ApplicationRole> _roleManager;
  24.  
  25. public RoleController(UserManager<ApplicationUser> userManager,
  26. RoleManager<ApplicationRole> roleManager)
  27. {
  28. _roleManager = roleManager;
  29. _userManager = userManager;
  30. }
  31. [TempData]
  32. public string ErrorMessage { get; set; }
  33.  
  34. [HttpGet]
  35. public ActionResult Index() {
  36.  
  37. var dd = _roleManager.Roles.Include(d => d.UserRoles).Select(o => new
  38. {
  39. o.Id,
  40. o.Name,
  41. userlist = o.UserRoles.Select(t => t.UserId).ToList(),
  42. }).Select(t => new {t.Id,t.Name,
  43. useridlist = string.Join(",", t.userlist)
  44. });
  45. List<RoleViewModels> list = new List<RoleViewModels>();
  46.  
  47. foreach (var gg in dd)
  48. {
  49. var pp = _userManager.Users.Where(o => gg.useridlist.Contains(o.Id)).Select(o => o.UserName).ToList();
  50.  
  51. list.Add( new RoleViewModels { Id= gg.Id,Role=gg.Name, Name = string.Join(",", pp) });
  52.  
  53. }
  54.  
  55. return View(list);
  56. // return View(_roleManager.Roles.Include(d => d.UserRoles));
  57. }
  58.  
  59. [HttpGet]
  60. public ActionResult Create() {
  61. return View();
  62. }
  63.  
  64. [HttpPost]
  65. public async Task<ActionResult> Create(RoleViewModels model)
  66. {
  67. if (ModelState.IsValid) {
  68. IdentityResult result = await _roleManager.CreateAsync(new ApplicationRole{Name=model.Name});
  69. if (result.Succeeded) {
  70.  
  71. var officeClaim = new Claim("office", model.OfficeNumber.ToString(), ClaimValueTypes.String);
  72. await _roleManager.AddClaimAsync(await _roleManager.FindByNameAsync(model.Name), officeClaim);
  73.  
  74. return RedirectToAction("Index");
  75. } else {
  76. AddErrors(result);
  77. }
  78. }
  79. return View(model);
  80. }
  81.  
  82. [HttpPost]
  83. public async Task<ActionResult> Delete(string id) {
  84. ApplicationRole role = await _roleManager.FindByIdAsync(id);
  85. if (role != null) {
  86. IdentityResult result = await _roleManager.DeleteAsync(role);
  87. if (result.Succeeded) {
  88. return RedirectToAction("Index");
  89. } else {
  90. return View("Error", result.Errors);
  91. }
  92. } else {
  93. return View("Error", new string[] { "Role Not Found" });
  94. }
  95. }
  96.  
  97. public async Task<ActionResult> Edit(string id) {
  98. ApplicationRole role = await _roleManager.FindByIdAsync(id);
  99. var temp = _roleManager.Roles.Include(d => d.UserRoles).Where(d => d.Id == id)
  100. .Select(d => new
  101. {
  102. d.UserRoles
  103. }).ToArray();
  104. string[] memberID = temp[].UserRoles.Select(x => x.UserId).ToArray();
  105. var members = _userManager.Users.Where(x => memberID.Any(y => y == x.Id));
  106. var nonMembers = _userManager.Users.Except(members);
  107.  
  108. return View(new RoleEditModel {
  109. Role = role,
  110. Members = members,
  111. NonMembers = nonMembers
  112. });
  113. }
  114.  
  115. [HttpPost]
  116. public async Task<ActionResult> Edit(RoleModificationModel model) {
  117. IdentityResult result;
  118. if (ModelState.IsValid) {
  119. foreach (string userId in model.IdsToAdd ?? new string[] { }) {
  120. result = await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(userId), model.RoleName);
  121. if (!result.Succeeded) {
  122. return View("Error", result.Errors);
  123. }
  124. }
  125. foreach (string userId in model.IdsToDelete ?? new string[] { }) {
  126. result = await _userManager.RemoveFromRoleAsync(await _userManager.FindByIdAsync(userId),
  127. model.RoleName);
  128. if (!result.Succeeded) {
  129. return View("Error", result.Errors);
  130. }
  131. }
  132. return RedirectToAction("Index");
  133. }
  134. return View("Error", new string[] { "Role Not Found" });
  135. }
  136.  
  137. private void AddErrors(IdentityResult result)
  138. {
  139. foreach (var error in result.Errors)
  140. {
  141. ModelState.AddModelError(string.Empty, error.Description);
  142. }
  143. }
  144. }
  145. }

Models->RoleViewModels->RoleViewModels.cs 新建

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6.  
  7. namespace IdentityMvc.Models.RoleViewModels
  8. {
  9. public class RoleViewModels
  10. {
  11. public string Id { get; set; }
  12.  
  13. public string Name { get; set; }
  14.  
  15. public string Role { get; set; }
  16.  
  17. public string OfficeNumber { get; set; }
  18. }
  19. public class RoleEditModel
  20. {
  21. public ApplicationRole Role { get; set; }
  22. public IEnumerable<ApplicationUser> Members { get; set; }
  23. public IEnumerable<ApplicationUser> NonMembers { get; set; }
  24. }
  25. public class RoleModificationModel {
  26. [Required]
  27. public string RoleName { get; set; }
  28. public string[] IdsToAdd { get; set; }
  29. public string[] IdsToDelete { get; set; }
  30. }
  31. }

Views->Role->Create.cshtml

  1. @model RoleViewModels
  2. @{ ViewBag.Title = "Create Role";}
  3. <h2>Create Role</h2>
  4. @Html.ValidationSummary(false)
  5. @using (Html.BeginForm()) {
  6. <div class="form-group">
  7. <label asp-for="Name" class="control-label"></label>
  8. <input asp-for="Name" class="form-control" />
  9. <span asp-validation-for="Name" class="text-danger"></span>
  10. </div>
  11. <div class="form-group">
  12. <label asp-for="OfficeNumber" class="control-label"></label>
  13. <input asp-for="OfficeNumber" class="form-control" />
  14. <span asp-validation-for="OfficeNumber" class="text-danger"></span>
  15. </div>
  16.  
  17. <button type="submit" class="btn btn-primary">Create</button>
  18. @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
  19. }

Views->Role->Edit.cshtml

  1. @model RoleEditModel
  2. @{ ViewBag.Title = "Edit Role";}
  3. @Html.ValidationSummary()
  4. @using (Html.BeginForm()) {
  5. <input type="hidden" name="roleName" value="@Model.Role.Name" />
  6. <div class="panel panel-primary">
  7. <div class="panel-heading">Add To @Model.Role.Name</div>
  8. <table class="table table-striped">
  9. @if (Model.NonMembers == null) {
  10. <tr><td colspan="">All Users Are Members</td></tr>
  11. } else {
  12. <tr><td>User ID</td><td>Add To Role</td></tr>
  13. foreach (ApplicationUser user in Model.NonMembers) {
  14. <tr>
  15. <td>@user.UserName</td>
  16. <td>
  17. <input type="checkbox" name="IdsToAdd" value="@user.Id">
  18. </td>
  19. </tr>
  20. }
  21. }
  22. </table>
  23. </div>
  24. <div class="panel panel-primary">
  25. <div class="panel-heading">Remove from @Model.Role.Name</div>
  26. <table class="table table-striped">
  27. @if (Model.Members == null) {
  28. <tr><td colspan="">No Users Are Members</td></tr>
  29. } else {
  30. <tr><td>User ID</td><td>Remove From Role</td></tr>
  31. foreach (ApplicationUser user in Model.Members) {
  32. <tr>
  33. <td>@user.UserName</td>
  34. <td>
  35. <input type="checkbox" name="IdsToDelete" value="@user.Id">
  36. </td>
  37. </tr>
  38. }
  39. }
  40. </table>
  41. </div>
  42. <button type="submit" class="btn btn-primary">Save</button>
  43. @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
  44. }

Views->Role->Index.cshtml

  1. @model IEnumerable<RoleViewModels>
  2. @using IdentityMvc.App_Code
  3. @{ ViewBag.Title = "Roles"; }
  4.  
  5. <div class="panel panel-primary">
  6. <div class="panel-heading">Roles</div>
  7. <table class="table table-striped">
  8.  
  9. <tr><th>ID</th><th>Name</th><th>Users</th><th></th></tr>
  10. @if (Model.Count() == ) {
  11. <tr><td colspan="" class="text-center">No Roles</td></tr>
  12. } else {
  13. foreach (RoleViewModels role in Model) {
  14. <tr>
  15. <td>@role.Id</td>
  16. <td>@role.Role</td>
  17. <td>@role.Name
  18. </td>
  19. <td>
  20. @using (Html.BeginForm("Delete", "Role",
  21. new { id = role.Id })) {
  22. @Html.ActionLink("Edit", "Edit", new { id = role.Id },
  23. new { @class = "btn btn-primary btn-xs" })
  24. <button class="btn btn-danger btn-xs"
  25. type="submit">
  26. Delete
  27. </button>
  28. }
  29. </td>
  30. </tr>
  31. }
  32. }
  33. </table>
  34. </div>
  35. @Html.ActionLink("Create", "Create", null, new { @class = "btn btn-primary" })

Startup.cs->ConfigureServices

  1. services.AddIdentity<ApplicationUser, IdentityRole>() -> services.AddIdentity<ApplicationUser, ApplicationRole>()

mvc core2.1 Identity.EntityFramework Core ROle和用户绑定查看 (八)完成的更多相关文章

  1. mvc core2.1 Identity.EntityFramework Core 配置 (一)

    https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/customize_identity_model?view=a ...

  2. mvc core2.1 Identity.EntityFramework Core 实例配置 (四)

    https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/customize_identity_model?view=a ...

  3. mvc core2.1 Identity.EntityFramework Core 用户Claims查看(七)

    添加角色属性查看 Views ->Shared->_Layout.cshtml <div class="navbar-collapse collapse"> ...

  4. mvc core2.1 Identity.EntityFramework Core 导航状态栏(六)

    之前做的无法 登录退出,和状态,加入主页导航栏 Views ->Shared->_Layout.cshtml <div class="navbar-collapse col ...

  5. mvc core2.1 Identity.EntityFramework Core 注册 (二)

    Startup.cs-> Configure app.UseAuthentication(); //启动验证 Controllers->AccountController.cs 新建 us ...

  6. mvc core2.1 Identity.EntityFramework Core 用户列表预览 删除 修改 (五)

    用户列表预览 Controllers->AccountController.cs [HttpGet] public IActionResult Index() { return View(_us ...

  7. mvc core2.1 Identity.EntityFramework Core 登录 (三)

    Controllers->AccountController.cs 新建 [HttpGet] [AllowAnonymous] public async Task<IActionResul ...

  8. webapi core2.1 Identity.EntityFramework Core进行配置和操作数据 (一)没什么用

    https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.1&am ...

  9. webapi core2.1 IdentityServer4.EntityFramework Core进行配置和操作数据

    https://identityserver4.readthedocs.io/en/release/quickstarts/8_entity_framework.html 此连接的实践 vscode ...

随机推荐

  1. 机器学习---笔记----Python基础

    一. python简介 1. python 具有丰富强大的库,常被称为胶水语言,能够把用其他语言制作的各种模块很轻松地联结在一起 2. python强制使用空白符(white space)作为语句缩进 ...

  2. java的小程序在html中的运行测试

    java的小程序在html中的运行测试,打开vs2012,以网站模式打开,生成,调用iis临时服务器运行.

  3. 一个非常适合IT团队的在线API文档、技术文档工具 (ShowDoc)

    在逸橙呆了不到两年,开发时后端都有开发接口API,来到数库,好多后端开发和前端沟通是还是发doc文档,很不方便,我向cto反应,自己找到这个,老乡田雷(php,隔壁村的)也用过,可能某些原因选择其他的 ...

  4. בוא--来吧--IPA--希伯来语

    灰常好听的希伯来语歌曲, Rita唱得真好.

  5. [Leetcode 881]船救人 Boats to Save People 贪心

    [题目] The i-th person has weight people[i], and each boat can carry a maximum weight of limit. Each b ...

  6. 深入理解java虚拟机---内存分配策略(十三)

    转载请注明原文地址:https://blog.csdn.net/initphp/article/details/30487407 Java内存分配策略 使用的ParNew+Serial Old收集器组 ...

  7. log4net 2.0.8 不支持core 数据库记录日志

    经过反编译log4net 标准库的代码,原本有的数据库链接AdoNetAppender 在core里面引用的,没有掉了. 可能新版本会有.

  8. 重载的方式写Python的post请求

    #encoding=utf-8#__author__="Lanyangyang" import unittestimport requestsimport json # This ...

  9. http 性能测试. Apache ab 使用.

    参数: 1.       ab -n 100 -c 10 地址:   请求100次, 并发10次. 2.  ab -n 100 -c 10 -w 地址:   请求100次, 并发10次 ,html 表 ...

  10. Node.js 回调函数 1) 阻塞 ,同步 2) 非阻塞 ,异步.

    1.阻塞. 同步. 1) 读取的文件: input.txt 菜鸟教程官网地址:www.runoob.com 2) main.js var fs = require("fs"); / ...