Identity 2.0 _LoginPartial Name
My MVC5 C # application, I extended ApplicationUser model to include first and last name, works well. I'm trying to figure out how I can change loginPartial to display the user's actual name and not their email address in the following code:
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
source to share
Above was my question, unfortunately I could not log into my old account. This is how I did it:
In Account Controller / Login I added the following:
var user = await UserManager.FindByNameAsync(model.UserName);
var t = await UserManager.AddClaimAsync(user.Id, new Claim("FullName", user.FirstName + " " + user.LastName));
Add this class:
public static class GenericPrincipalExtensions
{
public static string FullName (this IPrincipal user)
{
if (user.Identity.IsAuthenticated)
{
var claimsIdentity = user.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
foreach (var claim in claimsIdentity.Claims)
{
if (claim.Type == "FullName")
return claim.Value;
}
}
return "";
}
else
return "";
}
}
Please see Brendan Green's comments above, thanks to Brendan for the leadership. Changed _LoginPartial to:
@Html.ActionLink("Hello " + User.FullName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new {title = "Manage" })
source to share
You can do this quite easily by adding the NameName claim type. This code was generated and tested using the default mvc5 / web application visual studio template, which uses the asp.net id 2.
AccountController.cs
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
//Add the Full name claim, or any other potential claim information.
var userClaims = User as ClaimsPrincipal;
var identity = userClaims.Identity as ClaimsIdentity;
identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FullName));
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
_LoginPartial.cshtml
@Html.ActionLink("Hello " + System.Security.Claims.ClaimsPrincipal.Current.FindFirst(System.IdentityModel.Claims.ClaimTypes.GivenName).Value + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
Note that code like this can be hairy, so you can create an extension method that gets a name and looks cleaner.
source to share