Role based security in ASP.NET MVC5

Bài này hướng dẫn xây dựng xây dựng Role based security trong ASP.NET MVC5 kết hợp ASP.NET Identity có fix lỗi (nếu tham khảo hướng dẫn của các bài viết).

Bài này hoàn thành gồm các chức năng:

  • Register
  • Create a new role 
  • AddUserToRole
  • Edit role
  • Delete role
  • List all roles
  • List all roles was assigned for the user
  • Update role

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RoleAddToUser(string UserName, string RoleName)
{
ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
//var account = new AccountController();
//account.UserManager.AddToRoleAsync(user.Id, RoleName);
if (user != null) UserManager.AddToRole(user.Id, RoleName);
ViewBag.ResultMessage = “Role created successfully !”;

// prepopulat roles for the view dropdown
var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = list;

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

Link download mã nguồn

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s