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

前端 未结 4 569
鱼传尺愫
鱼传尺愫 2020-12-03 10:33

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.

相关标签:
4条回答
  • 2020-12-03 11:11

    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)

    0 讨论(0)
  • 2020-12-03 11:14

    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");
    
    0 讨论(0)
  • 2020-12-03 11:21

    this worked for me hope this helps...

    If HttpContext.Current.User.IsInRole("admin") Then
            adminmnu.Visible = True
        End If
    
    0 讨论(0)
  • 2020-12-03 11:30

    The correct way in ASP Identity is as simple as

    User.IsInRole("rolename");
    
    0 讨论(0)
提交回复
热议问题