我正在创建金融应用程序。我正在使用 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/