ASP.NET Identity 2.0检查当前用户是否处于角色IsInRole中

use*_*155 16 c# asp.net identity

使用ASP.NET Identity 2.0,您如何检查当前登录的用户是否在角色中?我正在使用以下内容,但想知道是否有更高效的东西.

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)
{
}
Run Code Online (Sandbox Code Playgroud)

blu*_*uee 33

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

User.IsInRole("rolename");
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,这仅在用户登录时有效。 (2认同)
  • 我想这种方式将检查ClaimsIdentity中的角色。例如,如果登录了User1,然后将User1添加到Group1,则User1.IsInRole(“ Group1”)= false。User1需要注销登录。 (2认同)

Rob*_*ein 7

假设您在ASP.NET中,它非常简单:

if (!Roles.IsUserInRole(User.Identity.Name, "Administrators"))
{
  return "You are not authorized to access this page.";
)
Run Code Online (Sandbox Code Playgroud)

(来自http://msdn.microsoft.com/en-us/library/4z6b5d42%28v=vs.110%29.aspx)


小智 6

您可以从Identity获取用户ID,而不必在数据库中查找用户...

var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DbContext()));
var inrole = um.IsInRole(Context.User.Identity.GetUserId(), "Admin");
Run Code Online (Sandbox Code Playgroud)