asp.net-mvc 获取当前用户的角色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2068445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get current user's role
提问by Ciel
Is there any way to get the explicit role that a user belongs to in my controller? This assumes using ASP.NET Membership and Role Providers. "IsInRole" doesn't work - I need to actually get the name of the role they are in.
有没有办法在我的控制器中获得用户所属的显式角色?这假定使用 ASP.NET 成员身份和角色提供程序。“IsInRole”不起作用 - 我需要实际获得他们所在角色的名称。
采纳答案by keyboardP
回答by Eilon
A user can be in more than one role so you can't get the onerole that the user is in, but you can easily get the listof roles a user is in.
一个用户可以担任多个角色,因此您无法获得该用户所担任的单一角色,但您可以轻松获得该用户所担任的角色列表。
You can use the Rolestype to get the list of roles that the currently logged in user is in:
您可以使用该Roles类型来获取当前登录用户所在的角色列表:
public ActionResult ShowUserRoles() {
string[] roleNames = Roles.GetRolesForUser();
return View(roleNames);
}
Or if you want to get the roles for an arbitrary user you can pass in the username when you call Roles.GetRolesForUser().
或者,如果您想获取任意用户的角色,您可以在调用时传入用户名Roles.GetRolesForUser()。
回答by Oracular Man
Simplemembership in MVC4:
MVC4 中的简单成员资格:
Getting the User's role-
获取用户的角色-
var role = System.Web.Security.Roles.GetRolesForUser().Single();
To check if the user belongs to a certain role-
检查用户是否属于某个角色 -
if (User.IsInRole("External"))
回答by Martyj
You can get the current user's role with Roles.GetRolesForUser().
您可以使用 获取当前用户的角色Roles.GetRolesForUser()。
To check if a user belongs to a role here is what I did:
要检查用户是否属于这里的角色,我是这样做的:
Roles.GetRolesForUser().Contains("Administrator")
回答by hug
I don't know if I'm missing some weird setting or setup, but I cannot get e.g. User.IsInRoleor Roles.GetRolesForUser()to work. I just get an exception (I think null reference), and the application just halts. Even though I have configured a RoleManager to the OwinContext and a Create method etc. like in the Identity Sample project by Microsoft, as well as enabled Role Manager in web.config.
I solved this at first using another approach, like this (db is the ApplicationDbContext):
我不知道我是否遗漏了一些奇怪的设置或设置,但我无法获得例如User.IsInRole或Roles.GetRolesForUser()工作。我只是得到一个异常(我认为是空引用),应用程序就停止了。即使我在 Microsoft 的 Identity Sample 项目中为 OwinContext 配置了 RoleManager 和 Create 方法等,并在 web.config 中启用了角色管理器。我首先使用另一种方法解决了这个问题,就像这样(db 是 ApplicationDbContext):
var UserID = User.Identity.GetUserId();
var userRoles = db.Roles.Include(r => r.Users).ToList();
var userRoleNames = (from r in userRoles
from u in r.Users
where u.UserId == UserID
select r.Name).ToList();
This may not be the most optimized way and can possibly be altered to a simplier form but it worked for me and may not require as much setup/dependencies as other approaches. The second approach is this (add this to your controller class):
这可能不是最优化的方式,可能会更改为更简单的形式,但它对我有用,并且可能不需要像其他方法那样多的设置/依赖项。第二种方法是这样的(将此添加到您的控制器类中):
private ApplicationDbContext db = new ApplicationDbContext();
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
set
{
_userManager = value;
}
}
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
Inside your controller you can now do e.g.:
在您的控制器中,您现在可以执行以下操作:
var UserID = User.Identity.GetUserId();
var RolesForUser = await UserManager.GetRolesAsync(UserID);
I'm using ASP.NET MVC 5 application just to be clear. The RoleManager isn't used in this example but it can be used for creating, finding, updating etc. roles. Using this approach allows for async calls using await, in case that is a benefit for your application.
为了清楚起见,我正在使用 ASP.NET MVC 5 应用程序。此示例中未使用 RoleManager,但它可用于创建、查找、更新等角色。使用这种方法允许使用 await 进行异步调用,以防这对您的应用程序有好处。
回答by Yitzhak Weinberg
I Use this code
我使用此代码
((ClaimsIdentity)User.Identity).FindAll(ClaimTypes.Role).ToList()
.OrderBy(x => x.Value == "admin" ? 1
: x.Value == "Salesperson" ? 2
: x.Value == "User" ? 3 : 4).First().Value
回答by Ahmed Kamal
if you want to get the role name of any user, then simply use following two functions in the controller you want to perform action .
如果您想获取任何用户的角色名称,那么只需在您要执行操作的控制器中使用以下两个函数即可。
public ApplicationSignInManager SignInManager
{
get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); }
private set { _signInManager = value; }
}
public ApplicationUserManager UserManager
{
get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
private set { _userManager = value; }
}
and then in the action , use the following line .
然后在操作中,使用以下行。
var role = UserManager.GetRoles(UserId);
note that here UserId is the id of ApplicationUser.
注意这里的 UserId 是 ApplicationUser 的 id。
this role will be IList
这个角色将是 IList
if your application logic is such that a user can be in only one role then you can access it by
如果您的应用程序逻辑使得用户只能担任一个角色,那么您可以通过以下方式访问它
string roleName = role[0];

