如何在ASP.Net MVC 5视图中获取ApplicationUser的自定义属性值?

Ian*_*Ian 8 c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我还使用Update-Databasein中的命令更新了数据库表Package-Manager Console,Visual Studio以确保ApplicationUser classAspNetUsers表之间的一致性.我已经确认调用的新列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>
Run Code Online (Sandbox Code Playgroud)

原来_LoginPartialView.cshtmlUser.Identity.GetUserName()用来得到UserNameApplicationUser.该User.IdentityGetUserIdName,AuthenticationType等...但我怎么得到我DisplayName的显示器?

tmg*_*tmg 12

在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

创建了一个从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;           
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的视图中使用它像:

User.Identity.GetDisplayName()
Run Code Online (Sandbox Code Playgroud)