C# mvc 5 检查用户角色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19689570/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:37:43 来源:igfitidea点击:
mvc 5 check user role
提问by Duke
How in mvc 5 I can found out role of logged user?
如何在 mvc 5 中找到登录用户的角色?
I made the user by this code
我通过这段代码创建了用户
private bool AddUserAndRole()
{
IdentityResult ir;
var rm = new RoleManager<IdentityRole>
(new RoleStore<IdentityRole>(new ApplicationDbContext()));
ir = rm.Create(new IdentityRole("admin"));
var user = new ApplicationUser() { UserName = "Admin" };
var result = UserManager.Create(user, "somepassword");
UserManager.AddToRole(user.Id, "admin");
return true;
}
After I loggin on site by that user. How in controller I can check if that user have role == "admin" or not? I found only one way which doesnt look works fast.
在我由该用户登录网站后。我如何在控制器中检查该用户是否具有角色 ==“管理员”?我发现只有一种看起来不快的方法。
var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var role = rm.FindByName("admin");
bool result = User.IsInRole(role.Name); //true
Do we have other ways?
我们还有其他方法吗?
采纳答案by Alex Dresko
bool result = User.IsInRole("admin")
Much easier. :)
容易多了。:)