Ответ 1
Если есть только определенные свойства, которые вам нужно получить, вы можете добавить их в качестве претензий в свой класс 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.Aut:
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();
Я бы рекомендовал кэширование, если вы вызываете это все это время.