Reputation: 1035
I'm using Membership Provider in my ASP.NET MVC Application . I want to check a user is admin or not .
if (Membership.ValidateUser(model.UserName, model.Password))
{
....
}
ValidateUser gets only Username and Password , I want to add another field ( IsAdmin ) . how can I write this code ?!
Upvotes: 0
Views: 727
Reputation: 30152
It's simply User.IsInRole("Administrators")
http://msdn.microsoft.com/en-us/library/system.web.security.roleprincipal.isinrole.aspx
Upvotes: 0
Reputation: 4458
As @jsalvy reminded me, you can just do this:
bool isUserAdmin = IsUserInRole(userName, "Admin");
The IsUserInRole
will return true if the user is in the role or false if not. You can also use string[] userRoles = Roles.GetRolesForUser(userName);
to get all the roles a user is in. And you can use the [Authorize(Roles = "Admin")]
attribute to restrict access to anyone who is not an admin.
Upvotes: 1
Reputation: 557
This should be done with an implementation of the RoleProvider, not the MembershipProvider, as the MembershipProvider does not handle permissions/roles.
http://msdn.microsoft.com/en-us/library/8fw7xh74.aspx is a brief overview of the RoleProvider base class. As you can see it contains methods like 'IsUserInRole' that allow you to check things like this.
Here's a more in-depth sample of how to implement it: http://msdn.microsoft.com/en-us/library/317sza4k.aspx
Aside from that, you can always create a MembershipManager class of some sort that directly checks against your DataSource whether a given user is or is not a member.
Edit: I wanted to clarify that you do not need to implement a provider on top of the RoleProvider with the standard setup.NET Membership/Role/Profile model. If you have roles setup for the users, you can access them with the Roles Class. The Roles class is to the RoleProvider, what the Membership class is to the MembershipProvider.
Upvotes: 0