ApplicationUser角色导航属性的ASP MVC生成引发警告

本文关键字:警告 MVC ASP 角色 导航 属性 ApplicationUser | 更新日期: 2023-09-27 17:59:40

我有以下应用程序用户模型:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<ApplicationRole> Roles { get; set; }
    public bool HasRole(string _role)
    {
        return Roles.Any(r => r.Name == _role);
    }
    public bool HasPermission(string _permission)
    {
        return Roles.Any(r => r.Permissions
              .Any(p => p.Name == _permission));
    }
}

但是当我运行构建时,我会收到以下警告消息:

ApplicationUser.Roles hides inherited member 
'IdentityUser<string, IdentityUserLogin,IdentityUserRole, IdentityUserClaim>.Roles. 
To make the current member override that implementation, add the overide keyword. Otherwise 
add the new keyword.

我的实现有问题吗?还是应该采取不同的方式?我添加了Roles导航属性,以便实现HasRole和HasPermission方法。

我的权限和ApplicationRole模型实现如下:

public class Permission
{
    public byte Id { get; set; }
    public string Name { get; set; }
    public virtual List<ApplicationRole> Roles { get; set; }
}

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }
    public ApplicationRole(string name) : base(name) { }
    public virtual ICollection<Permission> Permissions { get; set; }
    public bool IsPermissionInRole(string _permission)
    {
        return Permissions.Any(p => p.Name == _permission);
    }
}

ApplicationUser角色导航属性的ASP MVC生成引发警告

我对ASP.NET Identity没有广泛的了解。但经过一番搜索,我可以给你大致的答案IdentityUser应具有继承IdedentityUserRole而非Identity Role的项目角色。我认为这个模型将IdentityUsers和IdentityRoles联系起来。因此,您应该创建ApplicationUserRole类,该类继承IdentityUserRole:

public class ApplicationUserRole : IdentityUserRole
{
    public ApplicationUserRole()
        : base()
    { }
    public virtual ApplicationRole Role { get; set; }
}

IdentityRole<string, ApplicationUserRole>:继承ApplicationRole

public class ApplicationRole 
    : IdentityRole<string, ApplicationUserRole>
{
}

然后在ApplicationUser类中使用该类。要使用ApplicationUserRole,您需要从IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>而不是IdentityUser 继承ApplicationUser

public class ApplicationUser 
    : IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    .............
}

最后,将ApplicationUserHasPermission方法更改为类似的方法

public bool HasPermission(string _permission)
{
    return Roles.Any(r => r.Role.IsPermissionInRole(_permission));
}

我再次声明,这是粗略的答案。有关扩展身份模型的更多信息,请参阅这篇代码项目文章。