mvc core2.1 Identity.EntityFramework Core ROle和用户绑定查看 (八)完成
添加角色属性查看
Views ->Shared->_Layout.cshtml
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
- <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
- <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
- <li><a asp-area="" asp-controller="Account" asp-action="Index">Account</a></li>
- <li><a asp-area="" asp-controller="Claims" asp-action="Index">Claims</a></li>
- <li><a asp-area="" asp-controller="Role" asp-action="Index">Role</a></li> //加这句
Controllers ->RoleController.cs 新建
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using IdentityMvc.Models;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.AspNetCore.Authorization;
- using IdentityMvc.Models.AccountViewModels;
- using Microsoft.AspNetCore.Authentication;
- using System.ComponentModel.DataAnnotations;
- using Microsoft.EntityFrameworkCore;
- using IdentityMvc.Models.RoleViewModels;
- using System.Security.Claims;
- namespace IdentityMvc.Controllers
- {
- [Authorize]
- public class RoleController : Controller
- {
- private readonly UserManager<ApplicationUser> _userManager;
- private readonly RoleManager<ApplicationRole> _roleManager;
- public RoleController(UserManager<ApplicationUser> userManager,
- RoleManager<ApplicationRole> roleManager)
- {
- _roleManager = roleManager;
- _userManager = userManager;
- }
- [TempData]
- public string ErrorMessage { get; set; }
- [HttpGet]
- public ActionResult Index() {
- var dd = _roleManager.Roles.Include(d => d.UserRoles).Select(o => new
- {
- o.Id,
- o.Name,
- userlist = o.UserRoles.Select(t => t.UserId).ToList(),
- }).Select(t => new {t.Id,t.Name,
- useridlist = string.Join(",", t.userlist)
- });
- List<RoleViewModels> list = new List<RoleViewModels>();
- foreach (var gg in dd)
- {
- var pp = _userManager.Users.Where(o => gg.useridlist.Contains(o.Id)).Select(o => o.UserName).ToList();
- list.Add( new RoleViewModels { Id= gg.Id,Role=gg.Name, Name = string.Join(",", pp) });
- }
- return View(list);
- // return View(_roleManager.Roles.Include(d => d.UserRoles));
- }
- [HttpGet]
- public ActionResult Create() {
- return View();
- }
- [HttpPost]
- public async Task<ActionResult> Create(RoleViewModels model)
- {
- if (ModelState.IsValid) {
- IdentityResult result = await _roleManager.CreateAsync(new ApplicationRole{Name=model.Name});
- if (result.Succeeded) {
- var officeClaim = new Claim("office", model.OfficeNumber.ToString(), ClaimValueTypes.String);
- await _roleManager.AddClaimAsync(await _roleManager.FindByNameAsync(model.Name), officeClaim);
- return RedirectToAction("Index");
- } else {
- AddErrors(result);
- }
- }
- return View(model);
- }
- [HttpPost]
- public async Task<ActionResult> Delete(string id) {
- ApplicationRole role = await _roleManager.FindByIdAsync(id);
- if (role != null) {
- IdentityResult result = await _roleManager.DeleteAsync(role);
- if (result.Succeeded) {
- return RedirectToAction("Index");
- } else {
- return View("Error", result.Errors);
- }
- } else {
- return View("Error", new string[] { "Role Not Found" });
- }
- }
- public async Task<ActionResult> Edit(string id) {
- ApplicationRole role = await _roleManager.FindByIdAsync(id);
- var temp = _roleManager.Roles.Include(d => d.UserRoles).Where(d => d.Id == id)
- .Select(d => new
- {
- d.UserRoles
- }).ToArray();
- string[] memberID = temp[].UserRoles.Select(x => x.UserId).ToArray();
- var members = _userManager.Users.Where(x => memberID.Any(y => y == x.Id));
- var nonMembers = _userManager.Users.Except(members);
- return View(new RoleEditModel {
- Role = role,
- Members = members,
- NonMembers = nonMembers
- });
- }
- [HttpPost]
- public async Task<ActionResult> Edit(RoleModificationModel model) {
- IdentityResult result;
- if (ModelState.IsValid) {
- foreach (string userId in model.IdsToAdd ?? new string[] { }) {
- result = await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(userId), model.RoleName);
- if (!result.Succeeded) {
- return View("Error", result.Errors);
- }
- }
- foreach (string userId in model.IdsToDelete ?? new string[] { }) {
- result = await _userManager.RemoveFromRoleAsync(await _userManager.FindByIdAsync(userId),
- model.RoleName);
- if (!result.Succeeded) {
- return View("Error", result.Errors);
- }
- }
- return RedirectToAction("Index");
- }
- return View("Error", new string[] { "Role Not Found" });
- }
- private void AddErrors(IdentityResult result)
- {
- foreach (var error in result.Errors)
- {
- ModelState.AddModelError(string.Empty, error.Description);
- }
- }
- }
- }
Models->RoleViewModels->RoleViewModels.cs 新建
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Threading.Tasks;
- namespace IdentityMvc.Models.RoleViewModels
- {
- public class RoleViewModels
- {
- public string Id { get; set; }
- public string Name { get; set; }
- public string Role { get; set; }
- public string OfficeNumber { get; set; }
- }
- public class RoleEditModel
- {
- public ApplicationRole Role { get; set; }
- public IEnumerable<ApplicationUser> Members { get; set; }
- public IEnumerable<ApplicationUser> NonMembers { get; set; }
- }
- public class RoleModificationModel {
- [Required]
- public string RoleName { get; set; }
- public string[] IdsToAdd { get; set; }
- public string[] IdsToDelete { get; set; }
- }
- }
Views->Role->Create.cshtml
- @model RoleViewModels
- @{ ViewBag.Title = "Create Role";}
- <h2>Create Role</h2>
- @Html.ValidationSummary(false)
- @using (Html.BeginForm()) {
- <div class="form-group">
- <label asp-for="Name" class="control-label"></label>
- <input asp-for="Name" class="form-control" />
- <span asp-validation-for="Name" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="OfficeNumber" class="control-label"></label>
- <input asp-for="OfficeNumber" class="form-control" />
- <span asp-validation-for="OfficeNumber" class="text-danger"></span>
- </div>
- <button type="submit" class="btn btn-primary">Create</button>
- @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
- }
Views->Role->Edit.cshtml
- @model RoleEditModel
- @{ ViewBag.Title = "Edit Role";}
- @Html.ValidationSummary()
- @using (Html.BeginForm()) {
- <input type="hidden" name="roleName" value="@Model.Role.Name" />
- <div class="panel panel-primary">
- <div class="panel-heading">Add To @Model.Role.Name</div>
- <table class="table table-striped">
- @if (Model.NonMembers == null) {
- <tr><td colspan="">All Users Are Members</td></tr>
- } else {
- <tr><td>User ID</td><td>Add To Role</td></tr>
- foreach (ApplicationUser user in Model.NonMembers) {
- <tr>
- <td>@user.UserName</td>
- <td>
- <input type="checkbox" name="IdsToAdd" value="@user.Id">
- </td>
- </tr>
- }
- }
- </table>
- </div>
- <div class="panel panel-primary">
- <div class="panel-heading">Remove from @Model.Role.Name</div>
- <table class="table table-striped">
- @if (Model.Members == null) {
- <tr><td colspan="">No Users Are Members</td></tr>
- } else {
- <tr><td>User ID</td><td>Remove From Role</td></tr>
- foreach (ApplicationUser user in Model.Members) {
- <tr>
- <td>@user.UserName</td>
- <td>
- <input type="checkbox" name="IdsToDelete" value="@user.Id">
- </td>
- </tr>
- }
- }
- </table>
- </div>
- <button type="submit" class="btn btn-primary">Save</button>
- @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
- }
Views->Role->Index.cshtml
- @model IEnumerable<RoleViewModels>
- @using IdentityMvc.App_Code
- @{ ViewBag.Title = "Roles"; }
- <div class="panel panel-primary">
- <div class="panel-heading">Roles</div>
- <table class="table table-striped">
- <tr><th>ID</th><th>Name</th><th>Users</th><th></th></tr>
- @if (Model.Count() == ) {
- <tr><td colspan="" class="text-center">No Roles</td></tr>
- } else {
- foreach (RoleViewModels role in Model) {
- <tr>
- <td>@role.Id</td>
- <td>@role.Role</td>
- <td>@role.Name
- </td>
- <td>
- @using (Html.BeginForm("Delete", "Role",
- new { id = role.Id })) {
- @Html.ActionLink("Edit", "Edit", new { id = role.Id },
- new { @class = "btn btn-primary btn-xs" })
- <button class="btn btn-danger btn-xs"
- type="submit">
- Delete
- </button>
- }
- </td>
- </tr>
- }
- }
- </table>
- </div>
- @Html.ActionLink("Create", "Create", null, new { @class = "btn btn-primary" })
Startup.cs->ConfigureServices
- services.AddIdentity<ApplicationUser, IdentityRole>() -> services.AddIdentity<ApplicationUser, ApplicationRole>()
mvc core2.1 Identity.EntityFramework Core ROle和用户绑定查看 (八)完成的更多相关文章
- mvc core2.1 Identity.EntityFramework Core 配置 (一)
https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/customize_identity_model?view=a ...
- mvc core2.1 Identity.EntityFramework Core 实例配置 (四)
https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/customize_identity_model?view=a ...
- mvc core2.1 Identity.EntityFramework Core 用户Claims查看(七)
添加角色属性查看 Views ->Shared->_Layout.cshtml <div class="navbar-collapse collapse"> ...
- mvc core2.1 Identity.EntityFramework Core 导航状态栏(六)
之前做的无法 登录退出,和状态,加入主页导航栏 Views ->Shared->_Layout.cshtml <div class="navbar-collapse col ...
- mvc core2.1 Identity.EntityFramework Core 注册 (二)
Startup.cs-> Configure app.UseAuthentication(); //启动验证 Controllers->AccountController.cs 新建 us ...
- mvc core2.1 Identity.EntityFramework Core 用户列表预览 删除 修改 (五)
用户列表预览 Controllers->AccountController.cs [HttpGet] public IActionResult Index() { return View(_us ...
- mvc core2.1 Identity.EntityFramework Core 登录 (三)
Controllers->AccountController.cs 新建 [HttpGet] [AllowAnonymous] public async Task<IActionResul ...
- webapi core2.1 Identity.EntityFramework Core进行配置和操作数据 (一)没什么用
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.1&am ...
- webapi core2.1 IdentityServer4.EntityFramework Core进行配置和操作数据
https://identityserver4.readthedocs.io/en/release/quickstarts/8_entity_framework.html 此连接的实践 vscode ...
随机推荐
- 机器学习---笔记----Python基础
一. python简介 1. python 具有丰富强大的库,常被称为胶水语言,能够把用其他语言制作的各种模块很轻松地联结在一起 2. python强制使用空白符(white space)作为语句缩进 ...
- java的小程序在html中的运行测试
java的小程序在html中的运行测试,打开vs2012,以网站模式打开,生成,调用iis临时服务器运行.
- 一个非常适合IT团队的在线API文档、技术文档工具 (ShowDoc)
在逸橙呆了不到两年,开发时后端都有开发接口API,来到数库,好多后端开发和前端沟通是还是发doc文档,很不方便,我向cto反应,自己找到这个,老乡田雷(php,隔壁村的)也用过,可能某些原因选择其他的 ...
- בוא--来吧--IPA--希伯来语
灰常好听的希伯来语歌曲, Rita唱得真好.
- [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 ...
- 深入理解java虚拟机---内存分配策略(十三)
转载请注明原文地址:https://blog.csdn.net/initphp/article/details/30487407 Java内存分配策略 使用的ParNew+Serial Old收集器组 ...
- log4net 2.0.8 不支持core 数据库记录日志
经过反编译log4net 标准库的代码,原本有的数据库链接AdoNetAppender 在core里面引用的,没有掉了. 可能新版本会有.
- 重载的方式写Python的post请求
#encoding=utf-8#__author__="Lanyangyang" import unittestimport requestsimport json # This ...
- http 性能测试. Apache ab 使用.
参数: 1. ab -n 100 -c 10 地址: 请求100次, 并发10次. 2. ab -n 100 -c 10 -w 地址: 请求100次, 并发10次 ,html 表 ...
- Node.js 回调函数 1) 阻塞 ,同步 2) 非阻塞 ,异步.
1.阻塞. 同步. 1) 读取的文件: input.txt 菜鸟教程官网地址:www.runoob.com 2) main.js var fs = require("fs"); / ...