在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
table 。我已经确认名为 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()
关于c# - 如何在 ASP.Net MVC 5 View 中获取 ApplicationUser 的自定义属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38846816/