在视图中获取ASP.NET Identity的当前用户
在视图中获取ASP.NET Identity的当前用户
我正在使用ASP.NET Identity 2.0和MVC。我需要在视图中获取已登录用户的姓名,姓氏,电子邮件等信息。如何获取?我只能获取@User.Identity,但没有我的用户类的属性。
//in my view, i need here my ApplicationUser class @User.Identity.Name //ApplicationUser class public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim> { public ApplicationUser() { this.CreatedDate = DateTime.Now; } public DateTime CreatedDate { get; set; } public string Name { get; set; } public string Surname { get; set; } public string TaxOffice { get; set; } }
admin 更改状态以发布 2023年5月24日
如果您正在使用.NET Core应用程序:
您可以轻松使用@inject
功能调用来注入UserManager
和SignInManager
。
在您的视图中添加以下内容:
@inject SignInManagerSignInManager @inject UserManager UserManager
注入后,您应该就能够使用UserManager
和SignInManager
方法。例如:
@if (SignInManager.IsSignedIn(User)) { Hello @UserManager.GetUserName(User) } else { }
注意当您需要引用当前登录用户时,请传递
User
对象。
如果只需要获取特定的属性,您可以将它们添加为声明到您的ApplicationUser类中,例如以下示例:
public async TaskGenerateUserIdentityAsync(UserManager 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( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), getUserIdCallback: (id) => (id.GetUserId ()) ) } });
。然后,您可以在视图或控制器中访问声明:
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();
。然而,如果您一直调用它,我建议进行缓存。