使用ASP.NET标识检索DAL中用户的角色 [英] Retrieve Role for a User in the DAL using ASP.NET Identity

查看:62
本文介绍了使用ASP.NET标识检索DAL中用户的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用ASP.NET Identity的用户和角色的沼泽标准实现:

 公共类User:IdentityUserBase {}公共类角色:IdentityRoleBase {}公共类UserRole:IdentityUserRoleBase {} 

我需要User类中的属性或方法来返回用户的(第一个)角色(在我的应用中,每个用户只能有一个):

 公共类User:IdentityUserBase{//...公共角色GetRole(){返回this.Roles.FirstOrDefault();//实际上返回一个UserRole对象,只有一个UserId和一个RoleId(没有Role对象)}} 

在DAL中有没有办法做到这一点?

我知道可以在UI层上使用诸如RoleManager,DbContext或HTTPContext之类的全局对象,但我无权访问User类中的对象(也不必将其作为参数传递)./p>

我本以为这一定是一个标准用例,但我找不到答案……我的问题与解决方案

此方法有效:

 公共类UserRole:IdentityUserRoleBase{公共虚拟角色Role {get;放;}//添加它以查看角色公共虚拟用户User {get;放;}//添加它以查看用户} 

User Role 属性现在通过 User 对象提供的 UserRole 属性公开

回顾ASP.NET身份的演变此处,这些属性存在在版本1中,默认情况下在 IdentityUserRole 中删除,然后在版本2中删除,以便支持通用主键,并建议使用 UserManager 类.但是,这对像我这样的情况没有帮助,因为这些情况需要在DAL中完成操作,并且无法轻松访问此类(或任何上下文类).既然我再也没有其他类型的主键了,那么这样做很安全.

I have a bog-standard implementation of Users and Roles using ASP.NET Identity:

public class User : IdentityUserBase { }
public class Role : IdentityRoleBase { }
public class UserRole : IdentityUserRoleBase { }

I need a property or method in the User class that returns the (first) role of the user (in my app, each user can only have one):

public class User : IdentityUserBase
{
  // ...
  public Role GetRole()
  {
    return this.Roles.FirstOrDefault(); // this actually returns a UserRole object, with only a UserId and a RoleId available (no Role object)
  }
}

Is there a way to do this here in the DAL?

I know it's possible at the UI layer using global objects like RoleManager, DbContext or HTTPContext but I don't have access to those in the User class (and don't want to have to pass them in as arguments).

I would have thought that this must be a standard use-case but I can't find an answer ... my question is basically the same as this one but I need access to the Role information within the User object itself.

解决方案

This worked:

public class UserRole : IdentityUserRoleBase
{
    public virtual Role Role { get; set; } // add this to see roles
    public virtual User User { get; set; } // add this to see users
}

The User and Role properties are now exposed through the UserRole property that is available through the User object.

Looking back through the evolution of ASP.NET Identity here, these properties were present in IdentityUserRole by default in version 1 but then removed in version 2 in order to support generic primary keys, with a recommendation to use the UserManager class. However, this doesn't help cases like mine where the operations need to be done in the DAL and don't have easy access to this class (or the any of the context classes). Given that I will never have any other type of primary key, it feels quite safe to do this.

这篇关于使用ASP.NET标识检索DAL中用户的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆