简体   繁体   中英

ASP.NET Identity 2.0 check if current user is in role IsInRole

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)
{
}

ASP身份的正确方法就是这么简单

User.IsInRole("rolename");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM