在ASP.Net MVC 5中,可以扩展ApplicationUser以拥有自定义属性。我已经扩展它,使其现在拥有一个名为DisplayName的新属性:
我还使用Visual Studio中的Package-Manager控制台中的Update-Database命令更新了数据库表,以确保ApplicationUser类和AspNetUsers表之间的一致性。我确认名为DisplayName的新列现在存在于AspNetUsers表中。 现在,我想使用
// 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表中。 现在,我想使用
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
以供显示?
IdentiyExtensions
方法放在哪里?在IdentityModels.cs
中吗?还是会创建一个特定命名约定的新文件? - Ianreturn claim.FindFirst("DisplayName")
,而是返回return claim.FindFirst("DisplayName").ToString().Substring(("DisplayName: ").Length);
--这是因为claim.FindFirst("DisplayName")
是Claim
类型,但return
需要是一个string
类型。另外,如果我不加上Substring
,它会显示DisplayName: myname
而不是只有myname
。 - IanFindFirstValue
方法(它不存在)。我是否缺少任何引用?感谢更新 - 无论如何,我已经接受了您的答案,因为它已经足够指向正确的答案。;) - Ian