asp.net identity 2.2.0 中角色啟用和基本使用(三)

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   使用   sp   

建立控制器

第一步:在controllers檔案夾上點右鍵》添加》控制器, 我這裡選的是“MVC5 控制器-空”,名稱設定為:RolesAdminController.cs

第二步:添加命名空間

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 RolesAdminController : Controller內添加如下代碼

        public RolesAdminController()        {        }        public RolesAdminController(ApplicationUserManager userManager,            ApplicationRoleManager roleManager)        {            UserManager = userManager;            RoleManager = roleManager;        }        private ApplicationUserManager _userManager;        public ApplicationUserManager UserManager        {            get            {                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();            }            set            {                _userManager = value;            }        }        private ApplicationRoleManager _roleManager;        public ApplicationRoleManager RoleManager        {            get            {                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();            }            private set            {                _roleManager = value;            }        }

第五步:修改ActionResult Index()
修改後為

public ActionResult Index()        {            return View(RoleManager.Roles);//顯示角色清單        }

第六步:添加非同步顯示角色詳情

        //非同步顯示角色詳情        // GET: /Roles/Details/5        public async Task<ActionResult> Details(string id)        {            if (id == null)            {                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);            }            var role = await RoleManager.FindByIdAsync(id);            // 擷取角色內的使用者列表。
var users = new List<ApplicationUser>(); foreach (var user in UserManager.Users.ToList()) { if (await UserManager.IsInRoleAsync(user.Id, role.Name)) { users.Add(user); } } ViewBag.Users = users; ViewBag.UserCount = users.Count(); return View(role); }

第七步:添加建立角色

        //        //建立角色        // GET: /Roles/Create        public ActionResult Create()        {            return View();        }        //        // POST: /Roles/Create        [HttpPost]        public async Task<ActionResult> Create(RoleViewModel roleViewModel)        {            if (ModelState.IsValid)            {                var role = new IdentityRole(roleViewModel.Name);                var roleresult = await RoleManager.CreateAsync(role);                if (!roleresult.Succeeded)                {                    ModelState.AddModelError("", roleresult.Errors.First());                    return View();                }                return RedirectToAction("Index");            }            return View();        }

第八步:編輯角色

        //        //編輯角色        // GET: /Roles/Edit/Admin        public async Task<ActionResult> Edit(string id)        {            if (id == null)            {                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);            }            var role = await RoleManager.FindByIdAsync(id);            if (role == null)            {                return HttpNotFound();            }            RoleViewModel roleModel = new RoleViewModel { Id = role.Id, Name = role.Name };            return View(roleModel);        }        //        // POST: /Roles/Edit/5        [HttpPost]        [ValidateAntiForgeryToken]        public async Task<ActionResult> Edit([Bind(Include = "Name,Id")] RoleViewModel roleModel)        {            if (ModelState.IsValid)            {                var role = await RoleManager.FindByIdAsync(roleModel.Id);                role.Name = roleModel.Name;                await RoleManager.UpdateAsync(role);                return RedirectToAction("Index");            }            return View();        }

第九步:刪除角色

        //        //刪除角色        // GET: /Roles/Delete/5        public async Task<ActionResult> Delete(string id)        {            if (id == null)            {                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);            }            var role = await RoleManager.FindByIdAsync(id);            if (role == null)            {                return HttpNotFound();            }            return View(role);        }        //        // POST: /Roles/Delete/5        [HttpPost, ActionName("Delete")]        [ValidateAntiForgeryToken]        public async Task<ActionResult> DeleteConfirmed(string id, string deleteUser)        {            if (ModelState.IsValid)            {                if (id == null)                {                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);                }                var role = await RoleManager.FindByIdAsync(id);                if (role == null)                {                    return HttpNotFound();                }                IdentityResult result;                if (deleteUser != null)                {                    result = await RoleManager.DeleteAsync(role);                }                else                {                    result = await RoleManager.DeleteAsync(role);                }                if (!result.Succeeded)                {                    ModelState.AddModelError("", result.Errors.First());                    return View();                }                return RedirectToAction("Index");            }            return View();        }

至此,角色控制器就完成了。

 

asp.net identity 2.2.0 中角色啟用和基本使用(三)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.