在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;
}
}我还在Visual Studio的Package-Manager Console中使用Update-Database命令更新了数据库表,以确保ApplicationUser class和AspNetUsers表之间的一致性。我已经确认名为DisplayName的新列现在存在于AspNetUsers表中。

现在,我希望使用该DisplayName而不是原始_LoginPartial.cshtml View中的文本的默认UserName。但正如你所见:
<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()来获取ApplicationUser的UserName。User.Identity有GetUserId,也有Name,AuthenticationType等。但是如何让我的DisplayName显示出来呢?
发布于 2016-08-09 17:32:30
在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()https://stackoverflow.com/questions/38846816
复制相似问题