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

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

var um = new UserManager(new UserStore(new DbContext())); var au = um.FindByEmail(Context.User.Identity.GetUserName()); var inrole = um.IsInRole(au.Id, "Admin"); if (inrole) { } 

ASP身份的正确方法就像

 User.IsInRole("rolename"); 

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

 var um = new UserManager(new UserStore(new DbContext())); var inrole = um.IsInRole(Context.User.Identity.GetUserId(), "Admin"); 

假设您使用的是ASP.NET,它非常简单:

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

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

这对我有用,希望这有助于……

 If HttpContext.Current.User.IsInRole("admin") Then adminmnu.Visible = True End If