Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a Role to a user in MVC5?

In MVC4 I was using the code

Roles.AddUserToRole(User.Identity.Name, "Approved");

Is there any other way of doing the same(adding user to role "Approved") in MVC5 Identity Model?

EDIT: I meant to ask is this the right way of adding a user to a role? Because in a lot of examples they do not use this code.

like image 906
Flood Gravemind Avatar asked Jan 19 '14 13:01

Flood Gravemind


People also ask

What is difference between MVC4 and MVC5?

Identity feature in mvc4 is not available where as this is available in mvc5. 2. Authentication filter is not available in MVC4 where as Authentication filter is available in MVC5. Authentication filter is a new kind of filter in ASP.NET that runs prior to the authentication in MVC.


1 Answers

You can call AddToRole or AddToRoleAsync as an instance method on any object of type UserManager<TUser> to achieve it in MVC 5, like below:

var _context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
UserManager.AddToRole("UserName", "UserRole");

For more details, take a look at the following link:

http://msdn.microsoft.com/en-us/library/dn468199(v=vs.111).aspx

http://blogs.msdn.com/b/webdev/archive/2013/10/20/building-a-simple-todo-application-with-asp-net-identity-and-associating-users-with-todoes.aspx

like image 127
Lin Avatar answered Sep 20 '22 23:09

Lin