在业务层使用 asp.net 标识并添加属性

Use asp.net identity in business layer and add properties

我正在创建财务应用程序。我正在使用 asp.net 身份。当用户登录时,他们只会看到他们公司的记录。我有 GetRecords(int userID) 它 returns 用户公司的所有记录。

public List<FinanceData> GetRecords(int userID){
       int companyID = userService.GetCompanyID(userID);
       financeService.GetFinanceData(companyID);
 }

我的问题是:

1- 在 asp.net mvc 层中我可以访问 User.Identity.Name 但业务层(class 库)我无法访问此数据 属性。如何达到这个?

2- 我可以添加像 User.Identity.CompanyID 这样的属性吗?当用户登录时我该如何填写它。因为我不想为每个请求都去数据库。

我想这样使用我的方法:

public List<FinanceData> GetRecords(){
         financeService.GetFinanceData(User.Identity.CompanyID);
     }

Asp.net Identity 使用Claims 来存储用户信息,这种模型非常灵活,您完全可以向其中添加自定义声明,例如CompanyId。您必须在您的 ApplicationUser 或创建 ClaimsIdentity 的任何地方实施它,并向其中添加您的自定义声明。

(以下代码是从MVC模板中复制过来的)

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // **Add custom user claims here**
        return userIdentity;
    }
}

然后 ClaimsPrincipal 将通过 Thread.CurrentPrinciapl 在您的应用中的任何地方可用,即 运行 在同一个 AppDomain 中。因此,如果您的另一层不是 运行 作为其他地方的服务,您完全可以使用

var principal = Thread.CurrentPrincipal as ClaimsPrincipal

检查这是否不为空以及是否已通过身份验证,您应该可以开始了。

为了更加方便,您可以为 .CompanyId 的 ClaimsPrincipal 编写扩展方法。