默认身份带有一些用户属性。并且该表完全可以使用自定义属性进行扩展。
我添加了一个自定义属性“OrganisationId”来指定每个用户必须是组织的一部分。
public class ApplicationUser
: IdentityUser<int, ApplicationUserLogin,
ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public int OrganisationId { get; set; }
public Organisation Organisation { get; set; }
public UserProfile UserProfile { get; set; }
}
所以现在在我的大多数控制器中,我需要访问用户组织或用户组织ID来过滤内容。
例如:组织可以有多个地址,用户可以查看自己组织中的地址列表。
[ChildActionOnly]
// GET: Addresses
public ActionResult Index()
{
var userId = User.Identity.GetUserId<int>();
var userOrganisationId = _organisationService.GetOrganisationByUserId(userId).Id;
var addresses = _addressService.GetAddresses(userOrganisationId);
var viewModel = Mapper.Map<IEnumerable<Address>, IEnumerable<AddressViewModel>>(addresses);
return PartialView("_Index", viewModel);
}
但我可以看到,只获得访问我需要在我的控制器中注入ApplicationUserManager或OrganisationService的用户组织。
在上面你看到我已经注入了organisationService然后创建了一个查找用户组织的方法。
我只是认为这似乎是非常重复的任务。
这是否是在不注入任何服务的情况下访问用户扩展属性的任何其他更好的方法?
例如,用户对象已在控制器中访问。
就像是:
var organisationId = User.GetCustomProperty(u => u.OrganisationId);
或者也许使用自定义动作过滤器
什么是避免这种重复检查的最佳方法?
谢谢,
我找到的最简单的方法是以下两行代码,希望这对您有所帮助。
public class ApplicationUser : IdentityUser
{
[Required]
public string Name { get; set; }
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;
}
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
<ul class="nav navbar-nav navbar-left">
<li>
@{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
}
@Html.ActionLink(currentUser.Name + " " + "Welcome", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li>
<a href="javascript:document.getElementById('logoutForm').submit()">LogOff </a>
</li>
</ul>