2017-01-30 28 views
0

我已经添加了以下属性来我ApplicationUser类:如何以asp.net身份更改我的欢迎消息?

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}”,名字,姓氏)

我只是不知道如何扩展IdentityExtensions类,以添加一个函数,返回值想在这里。

我从哪里开始?

+0

我知道'User.Identity.Name',你有没有尝试,如果它适用于第一至少命名? –

回答

1

为此,您可以用Claims

添加claimIdentityModels.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; 
     } 

并添加此extensionExtension.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); 
+0

我目前没有在任何地方存储扩展名......现在基本上都是样板文件。 – Ortund

+0

你可以在任何静态类中放置扩展名,并且在使用它的时候不要忘记添加该静态类的名称空间 –

+0

得到它谢谢。当我找出如何将FirstName和LastName值添加到用户记录中时,它应该工作正常... – Ortund