我已将以下属性添加到我的ApplicationUser类:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
// if true, user will be subscribed to the Newsletter
public bool Newsletter { get; set; }
}
我的_LoginPartial页面显然还不知道这个并从IdentityExtensions获取数据:
@Html.ActionLink("Welcome back " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
GetUserName()
函数返回电子邮件地址。我更喜欢返回String.Format(" {0} {1}",FirstName,LastName)
我只是不知道如何扩展IdentityExtensions类,以便添加一个返回我想要的值的函数。
我从哪里开始?
答案 0 :(得分:1)
您可以使用Claims
将claim
添加到IdentityModels.cs
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("UserFullName", string.Format("{0} {1}", this.Name, this.Surname)));
return userIdentity;
}
并将此extension
添加到Extension.cs
或您存储扩展程序的地方
public static string GetUserFullName(this IIdentity identity)
{
string claim = ((ClaimsIdentity)identity).FindFirstValue("UserFullName").ToString();
return claim;
}
在此之后你可以使用
User.Identity.GetUserFullName()
修改强>
如果你不想使用extension
,你可以这样做
public string GetUserFullName(IIdentity identity)
{
string claim = ((ClaimsIdentity)identity).FindFirstValue("UserFullName").ToString();
return claim;
}
GetUserFullName(User.Identity);