With ASP.NET Identity 2.0 how do you check if the currently logged on user is in a role? I am using the following, but wondering if there is something more efficient.
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DbContext()));
var au = um.FindByEmail(Context.User.Identity.GetUserName());
var inrole = um.IsInRole(au.Id, "Admin");
if (inrole)
{
}
The correct way in ASP Identity is as simple as
User.IsInRole("rolename");
Robert Goldwein
Assuming you are in ASP.NET, it's pretty simple:
if (!Roles.IsUserInRole(User.Identity.Name, "Administrators"))
{
return "You are not authorized to access this page.";
)
(from http://msdn.microsoft.com/en-us/library/4z6b5d42%28v=vs.110%29.aspx)
You can get the user id from the Identity rather than having to lookup the user in the database...
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DbContext()));
var inrole = um.IsInRole(Context.User.Identity.GetUserId(), "Admin");
this worked for me hope this helps...
If HttpContext.Current.User.IsInRole("admin") Then
adminmnu.Visible = True
End If
来源:https://stackoverflow.com/questions/23049813/asp-net-identity-2-0-check-if-current-user-is-in-role-isinrole