c# – 获取ASP.NET身份当前用户在视图中
发布时间:2020-12-15 03:46:10 所属栏目:百科 来源:网络整理
导读:我使用ASP.NET Identity 2.0和MVC.我需要登录用户名,姓,电子邮件等.怎么可以得到它?我可以得到@ User.Identity,但没有我的用户类的属性. //in my view,i need here my ApplicationUser classdiv@User.Identity.Name/div//ApplicationUser classpublic class
|
我使用ASP.NET Identity 2.0和MVC.我需要登录用户名,姓,电子邮件等.怎么可以得到它?我可以得到@ User.Identity,但没有我的用户类的属性.
//in my view,i need here my ApplicationUser class
<div>
@User.Identity.Name
</div>
//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; }
}
解决方法
如果只有您需要获取的特定属性,您可以将它们作为您的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(); 不过,如果您一直在打电话给我,建议您使用缓存. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
