问题描述
我正在使用Identity 2在mvc 5网站中进行身份验证.在我看来,我想检查用户的角色:
I 'm using Identity 2 for authentication in mvc 5 web site. In my view i want check the role of the user :
@if(User.IsInRole("Customers"))
{
@*do something*@
}
,但这总是返回false,我已经在Web配置中设置了<roleManager enabled="true" />
.请帮忙.
but this always return false, I have already set <roleManager enabled="true" />
in the web config.any help please.
推荐答案
我刚将其用于也使用Identity Framework的安装程序.
I just got it to work with my setup that is also using Identity Framework.
我使用以下代码将用户添加到角色中:
I added a user to a role by using the following code:
this.RoleManager.CreateAsync(new Role() {Name = "Customers"});
this.UserManager.AddToRoleAsync(this.User.Identity.GetUserId<int>(), "Amazing");
然后在任何时候,当我运行User.IsInRole("Customers");
时,它返回false,直到我将它们重新登录.
Then any time after that, when I ran User.IsInRole("Customers");
it returned false, that was until I relogged them back in.
将用户添加到角色后,您需要重新登录用户.角色信息存储在cookie中.
You need to re-log in the user after having added the user to the role. The role information is stored in the cookies.
我运行以下命令再次登录用户:
I ran the following to log the user again:
var user = await this.UserManager.FindByNameAsync("bob");
var identity = await this.UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
this.AuthManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
从这一点来看,User.IsInRole("Customers")
为我工作并返回了true
.
From this point, User.IsInRole("Customers")
worked for me and returned true
.
但是,除非您可以在应用程序中确认它知道要添加它们的角色,否则这将无法工作.您可以通过以下方式使用RoleManager来验证角色"Customers"的存在:
This won't work though unless you can verify within your application that it is aware of the role that you want to add them to. You can verify the existence of the role "Customers" by using your RoleManager in the following way:
var roleExists = (this.RoleManager.FindByNameAsync("Customers").Result != null);
这篇关于User.IsInRole返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!