asp.net identity 2.2.0 中角色启用和基本使用(五)

时间:2023-07-22 18:07:56

建立控制器UsersAdminController

第一步:在controllers文件夹上点右键》添加》控制器, 我这里选的是“MVC5 控制器-空”,名称设置为:UsersAdminController.cs

第二步:添加命名空间

using System.Data.Entity;
using System.Net;
using System.Threading.Tasks;
using xxxx(项目名).Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;

第三步:在控制器的空间命名下添加权限(如果在第一讲中你选择了可选操作这里可以直接添加权限,否则要么改,要么先别填。)

[Authorize(Roles = "Admin")]

第四步:在public class UsersAdminController : Controller内添加如下代码

public UsersAdminController()
        {
        }

        public UsersAdminController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
        {
            UserManager = userManager;
            RoleManager = roleManager;
        }

        private ApplicationUserManager _userManager;
        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        private ApplicationRoleManager _roleManager;
        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set
            {
                _roleManager = value;
            }
        }

第五步:修改ActionResult Index()
修改后为

public async Task<ActionResult> Index()
        {
            return View(await UserManager.Users.ToListAsync());
        }

第六步:添加用户详情

//
        //异步读取用户详情
        //GET: /Users/Details/5
        public async  Task<ActionResult> Details(string id)
        {
            //用户为空时返回400错误
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            //按Id查找用户
            var user = await UserManager.FindByIdAsync(id);
            ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
            return View(user);
        }

第七步:添加用户创建

        //
        //异步读取用户创建
        //GET:/Users/Create
        public async Task <ActionResult>Create()
        {
            //读取角色列表
            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
            return View();
        }
        //
        //异步写入用户创建
        // POST: /Users/Create
        [HttpPost]
        public async Task <ActionResult> Create(RegisterViewModel userViewModel,params  string [] selectedRoles)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = userViewModel.Email, Email = userViewModel.Email };
                var adminresult = await UserManager.CreateAsync(user, userViewModel.Password);

                //
                if(adminresult.Succeeded)
                {
                    if(selectedRoles!=null)
                    {
                        var result = await UserManager.AddToRolesAsync(user.Id, selectedRoles);
                        if(!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First());
                            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
                            return View();
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());
                    ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
                    return View();
                }
                return RedirectToAction("Index");
            }
            ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
            return View();
        }

第八步:添加用户编辑

        //
        //读取用户编辑
        // GET: /Users/Edit/1
        public async  Task <ActionResult> Edit (string id)
        {
            if(id == null )
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = await UserManager.FindByIdAsync(id);
            if (user ==null )
            {
                return HttpNotFound();
            }
            var userRoles = await UserManager.GetRolesAsync(user.Id);
            return View(new EditUserViewModel()
                {
                    Id = user.Id,
                    Email = user.Email,
                    RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
                    {
                        Selected = userRoles.Contains(x.Name),
                        Text = x.Name,
                        Value = x.Name
                    })
                });
        }
        //
        //写入用户编辑
        // POST: /Users/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "Email,Id")]EditUserViewModel editUser, params string[] selectedRole)
        {
            if(ModelState.IsValid)
            {
                var user = await UserManager.FindByIdAsync(editUser.Id);
                if (user == null)
                {
                    return HttpNotFound();
                }
                user.UserName = editUser.Email;
                user.Email = editUser.Email;

                var userRoles = await UserManager.GetRolesAsync(user.Id);
                selectedRole = selectedRole ?? new string[] { };
                var result = await UserManager.AddToRolesAsync(user.Id, selectedRole.Except(userRoles).ToArray<string>());
                if(!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return View();
                }
                return RedirectToAction("Index");
            }
            ModelState.AddModelError("", "操作失败。");
            return View();
        }

第九步:添加用户删除

        //
        //读取用户删除
        // GET: /Users/Delete/5
        public async Task<ActionResult> Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = await UserManager.FindByIdAsync(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }
        //
        //写入角色删除
        // POST: /Users/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(string id)
        {
            if(ModelState.IsValid)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                var user = await UserManager.FindByIdAsync(id);
                if(user == null)
                {
                    return HttpNotFound();
                }
                var result = await UserManager.DeleteAsync(user);
                if(!result .Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return View();
                }
                return RedirectToAction("Index");
            }
            return View();
        }

至此,UsersAdmin控制器完成。