如果您只需要获取特定属性,则可以将它们作为声明添加到 ApplicationUser 类中,如下例所示:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> 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
userIdentity.AddClaim(new Claim("FullName", this.FullName));
// or use the ClaimTypes enumeration
return userIdentity;
}
这是从 Startup.Auth 类连接起来的:
SessionStateSection sessionStateSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/account/login"),
CookieName = sessionStateSection.CookieName + "_Application",
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>
(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (id) => (id.GetUserId<int>())
)
}
});
然后,您可以访问声明(在视图或控制器中):
var claims = ((System.Security.Claims.ClaimsIdentity)User.Identity).Claims;
var claim = claims.SingleOrDefault(m => m.Type == "FullName");
这里没有表单身份验证票。
如果您希望获得完整的用户详细信息,您始终可以创建如下扩展方法:
public static ApplicationUser GetApplicationUser(this System.Security.Principal.IIdentity identity)
{
if (identity.IsAuthenticated)
{
using (var db = new AppContext())
{
var userManager = new ApplicationUserManager(new ApplicationUserStore(db));
return userManager.FindByName(identity.Name);
}
}
else
{
return null;
}
}
然后这样称呼它:
@User.Identity.GetApplicationUser();
但是,如果您一直在调用它,我建议您进行缓存。