实施定制UserValidator
已经在这里介绍过:如何自定义 Asp.net Identity 2 用户名已采用验证消息?
不要为每个页面请求都访问数据库来显示句柄,而是在登录期间添加声明。
定义您自己的主张:
public static class CustomClaimTypes
{
public const string Handle = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/handle";
}
在登录过程中,设置声明:
private async Task SignInAsync(ApplicationUser user, bool isPersistent, string password = null)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
//Get the handle and add the claim to the identity.
var handle = GetTheHandle();
identity.AddClaim(new Claim(CustomClaimTypes.Handle, handle);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
然后,通过扩展方法,您可以按照与GetUserName()
:
public static class IdentityExtensions
{
public static string GetHandle(this IIdentity identity)
{
if (identity == null)
return null;
return (identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.Handle);
}
internal static string FirstOrNull(this ClaimsIdentity identity, string claimType)
{
var val = identity.FindFirst(claimType);
return val == null ? null : val.Value;
}
}
最后,在您看来:
@User.Identity.GetHandle()