Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc User.IsInRole返回false_Asp.net Mvc_Asp.net Identity_Roles - Fatal编程技术网

Asp.net mvc User.IsInRole返回false

Asp.net mvc User.IsInRole返回false,asp.net-mvc,asp.net-identity,roles,Asp.net Mvc,Asp.net Identity,Roles,我正在MVC5网站中使用Identity 2进行身份验证。在我看来,我想检查用户的角色: @if(User.IsInRole("Customers")) { @*do something*@ } 但这总是返回false,我已经在web配置中设置了。 请提供任何帮助。我刚刚将其用于我的设置,该设置也使用Identity Framework 我使用以下代码将用户添加到角色: this.RoleManager.CreateAsync(new Role() {Name = "Customers"

我正在MVC5网站中使用Identity 2进行身份验证。在我看来,我想检查用户的角色:

@if(User.IsInRole("Customers"))
{
  @*do something*@
}
但这总是返回false,我已经在web配置中设置了

请提供任何帮助。

我刚刚将其用于我的设置,该设置也使用Identity Framework

我使用以下代码将用户添加到角色:

this.RoleManager.CreateAsync(new Role() {Name  = "Customers"});

this.UserManager.AddToRoleAsync(this.User.Identity.GetUserId<int>(), "Amazing");
从这一点来看,
User.IsInRole(“客户”)
为我工作,并返回了
true

但是,除非您可以在应用程序中验证它是否知道您要将它们添加到的角色,否则这将不起作用。您可以通过以下方式使用角色管理器验证角色“客户”的存在:

var roleExists = (this.RoleManager.FindByNameAsync("Customers").Result != null);

由于我自定义了
IdentityDbContext
类,所以我也遇到了同样的问题。在我的例子中,
User.IsInRole(“Customers”)
总是错误的原因是我在自定义上下文类上关闭了EF延迟加载。我尝试打开延迟加载,然后注销并登录,
User.IsInRole
返回预期值

public partial class Context : IdentityDbContext<User>
    {
        public Context() : base("name=Context")
        {
            this.Configuration.LazyLoadingEnabled = true;          
        }
public分部类上下文:IdentityDbContext
{
公共上下文():基(“名称=上下文”)
{
this.Configuration.LazyLoadingEnabled=true;
}

对我来说,问题是在Startup类中,我没有像这样注册角色存储

services.AddDefaultIdentity()
.AddEntityFrameworkStores();

所以只要添加
.AddRoles()
,它就能为我解决问题

services.AddDefaultIdentity()
.AddRoles()

.AddEntityFrameworkStores()

最近我遇到了同样的问题,我在没有SSl的情况下运行应用程序,因此我的浏览器在启用SSl后拒绝了运行应用程序的cookie。为我解决了这个问题。

您的数据库是否表明用户确实担任了角色,角色名称是否准确无误?用户定义是否正确y已登录?即…如果向控制器添加
[Authorize]
,是否加载操作?角色名称正确,并且此用户的数据库中存在该角色。如果添加
[Authorize(Roles=“Customers”)]
操作是否加载?您是如何将用户添加到角色的?否,不加载。角色添加到后端:ApplicationUser user=UserManager.FindById(userId);UserManager.AddToRole(user.Id,roleName);嗯,非常奇怪。我必须承认,在你发布这个问题之前,我不知道这个方法存在。首先,我认为这是一个解决方案,但在我的情况下,故障是不确定的。根据我的调试,
LazyLoadingEnabled=true;
是默认值(MVC 5)
public partial class Context : IdentityDbContext<User>
    {
        public Context() : base("name=Context")
        {
            this.Configuration.LazyLoadingEnabled = true;          
        }