在mvc 5网站上,我使用标识2进行身份验证。在我看来,我希望检查用户的角色:
@if(User.IsInRole("Customers"))
{
@*do something*@
}但是这总是返回false,我已经在web配置中设置了<roleManager enabled="true" />。有什么帮助吗。
发布于 2015-05-21 09:48:19
我刚刚让它与我的设置,也是使用身份框架。
我使用以下代码向角色添加了一个用户:
this.RoleManager.CreateAsync(new Role() {Name = "Customers"});
this.UserManager.AddToRoleAsync(this.User.Identity.GetUserId<int>(), "Amazing");在此之后的任何时候,当我运行User.IsInRole("Customers");时,它都会返回false,直到我重新登录它们。
在将用户添加到角色后,您需要重新登录用户。角色信息存储在cookie中。
我运行了以下命令来再次记录用户:
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。
但是,除非您能够在应用程序中验证它是否知道要将它们添加到哪个角色,否则这是行不通的。您可以通过以下方式使用RoleManager来验证角色"Customers“的存在:
var roleExists = (this.RoleManager.FindByNameAsync("Customers").Result != null);发布于 2020-05-15 09:54:46
对我来说,问题是在启动类中,我没有像这样注册角色存储
services.AddDefaultIdentity<ApplicationUser>() .AddEntityFrameworkStores<ApplicationDbContext>();
所以只要加上.AddRoles<IdentityRole>(),它就能帮我解决这个问题
services.AddDefaultIdentity<ApplicationUser>() .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>();
发布于 2016-03-09 09:41:04
我也有同样的问题,因为我自定义了IdentityDbContext类。在我的情况下,User.IsInRole("Customers")总是错误的原因是因为我在自定义上下文类上关闭了EF延迟加载。我尝试打开延迟加载,而不是登录,然后User.IsInRole返回预期值。
public partial class Context : IdentityDbContext<User>
{
public Context() : base("name=Context")
{
this.Configuration.LazyLoadingEnabled = true;
}https://stackoverflow.com/questions/30369157
复制相似问题