c# - 在业务层使用asp.net身份并添加属性

标签 c# asp.net asp.net-mvc asp.net-identity

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

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

我的问题是:

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

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

我想像这样使用我的方法:

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

最佳答案

Asp.net身份使用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;
    }
}

然后,在同一 AppDomain 中运行的应用程序中的任何位置都可以通过 Thread.CurrentPrinciapl 来使用 ClaimsPrincipal。因此,如果您的其他层没有在其他地方作为服务运行,您完全可以使用

var principal = Thread.CurrentPrincipal as ClaimsPrincipal

检查这是否不为空以及是否已通过身份验证,然后就可以开始了。

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

关于c# - 在业务层使用asp.net身份并添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29259278/

相关文章:

c# - 使用 ASP.NET MVC 处理/接收来自 WebRTC 或任何基于浏览器的捕获机制到服务器的实时视频网络摄像头流

javascript - 发送 XMLHttpRequest 未与 Controller 方法绑定(bind)

c# - 如何在 C# 中使用 List<int> 作为 SQL 参数

c# MySqlCommand.Parameters.AddWithValue,参数表达一个表,结果命令添加了单引号

c# - 如何删除 Unicode 字符中的重音符号?

c# - Linq2SQL : Update object not created in datacontext

c# - 在 asp.net 中从 Web.config 获取连接字符串

asp.net-mvc - Controller 相当于 ASP.NET MVC 中的 HttpContext.Current

asp.net-mvc - Asp.net MVC 3中的自定义成员资格提供程序

c# - MySQL Entity Framework 按日期分组和选择