在中ASP.Net MVC 5
,ApplicationUser
可以扩展为具有自定义属性。我对其进行了扩展,以使其现在具有一个名为的新属性DisplayName
:
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser {
public string ConfirmationToken { get; set; }
public string DisplayName { get; set; } //here it is!
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> 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
return userIdentity;
}
}
我还使用中的Update-Database
命令更新了数据库表Package-Manager Console
,Visual Studio
以确保ApplicationUser
class
和AspNetUsers
表之间的一致性。我已经确认,表中DisplayName
现在存在新的列AspNetUsers
。
现在,我想使用它DisplayName
代替UserName
原始文本中的默认值_LoginPartial.cshtml
View
。但是如您所见:
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
原来_LoginPartialView.cshtml
是User.Identity.GetUserName()
用来获取UserName
的ApplicationUser
。该User.Identity
有GetUserId
还Name
,AuthenticationType
等...但我怎么得到我DisplayName
的显示器?
在ClaimsIdentity中添加索赔:
public class ApplicationUser : IdentityUser
{
...
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> 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("DisplayName", DisplayName));
return userIdentity;
}
}
创建一个扩展方法以从ClaimsIdentity读取DisplayName:
public static class IdentityExtensions
{
public static string GetDisplayName(this IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var ci = identity as ClaimsIdentity;
if (ci != null)
{
return ci.FindFirstValue("DisplayName");
}
return null;
}
}
在您看来,使用它的方式如下:
User.Identity.GetDisplayName()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句