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

9
在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控制台中的Update-Database命令更新了数据库表,以确保ApplicationUser类和AspNetUsers表之间的一致性。我确认名为DisplayName的新列现在存在于AspNetUsers表中。

enter image description here

现在,我想使用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()来获取ApplicationUserUserNameUser.Identity还有GetUserIdNameAuthenticationType等属性... 但我如何获取我的DisplayName以供显示?

1个回答

14
在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()

这看起来很有前途...你通常把IdentiyExtensions方法放在哪里?在IdentityModels.cs中吗?还是会创建一个特定命名约定的新文件? - Ian
我会创建一个名为“IdentityExtensions.cs”的新文件,可能位于名为“Helpers”的文件夹中。 - tmg
谢谢你的回答!它有效!我做了一点修改...不是返回return claim.FindFirst("DisplayName"),而是返回return claim.FindFirst("DisplayName").ToString().Substring(("DisplayName: ").Length);--这是因为claim.FindFirst("DisplayName")Claim类型,但return需要是一个string类型。另外,如果我不加上Substring,它会显示DisplayName: myname而不是只有myname - Ian
我找不到FindFirstValue方法(它不存在)。我是否缺少任何引用?感谢更新 - 无论如何,我已经接受了您的答案,因为它已经足够指向正确的答案。;) - Ian
它位于Microsoft.AspNet.Identity命名空间中。 - tmg
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接