扩展ASP.NET身份

从许多方面来看,这似乎已被多次询问,但这些似乎都不适合我的确切情况。

这是我的_LoginPartial.cshtml文件中的一行:

@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" }) 

请参阅说明User.Identity.GetUserName()的部分?

我想将其更改为User.Identity.FirstName或User.Identity.GetFirstName()。

我不希望它说“你好电子邮件地址”,而是“Hello Bob”

我的想法是,我只是想在Identity类上显示一个新的属性(或方法)。 显然它必须不止于此。

我添加了FirstName属性, 在AccountController中可用

 public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } 

它不会在_LoginPartial文件中公开。 我希望它暴露在那里!

谢谢您的帮助

即使你的答案不是“我想要的”,你的评论也让我得到了这个解决方案:

 @using Microsoft.AspNet.Identity @using YourModelnameHere.Models @if (Request.IsAuthenticated) { using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) { @Html.AntiForgeryToken()  } } 

在我的IdentityModel.cs文件中,我添加了两个属性FirstName和LastName

 public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } } 

我通过在用户登录时向声明添加名字和姓氏,然后编写我自己的扩展方法来完成此操作。

当用户登录时,将所需的详细信息添加到声明集( AccountController ):

 private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); // Add the users primary identity details to the set of claims. var pocoForName = GetNameFromSomeWhere(); identity.AddClaim(new Claim(ClaimTypes.GivenName, pocoForName)); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); } 

扩展方法,它只是从用户的声明集中提取细节:

 public static class IdentityExtensions { public static IdentityName GetGivenName(this IIdentity identity) { if (identity == null) return null; return (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.GivenName); } internal static string FirstOrNull(this ClaimsIdentity identity, string claimType) { var val = identity.FindFirst(claimType); return val == null ? null : val.Value; } } 

现在在partial中,只需调用新的扩展方法即可获得所需的详细信息:

 @Html.ActionLink("Hello " + User.Identity.GetGivenName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" }) 

编辑:更新以更紧密地匹配SignInAsync()方法的原始海报版本

 private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await user.GenerateUserIdentityAsync(UserManager); //add your claim here AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); } 

为Asp .net Core更新了答案! 希望这可以节省一些时间给其他用户。

 @if (SignInManager.IsSignedIn(User)){  

}