If you are using Asp.Net Identity, then this is very easy to do with claims.
In your SignInAsync
method (or, wherever you are creating the claims identity), add the GivenName
and Surname
claim types:
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 your_profile = GetFromYourProfileTable();
identity.AddClaim(new Claim(ClaimTypes.GivenName, your_profile == null ? string.Empty : your_profile.FirstName));
identity.AddClaim(new Claim(ClaimTypes.Surname, your_profile == null ? string.Empty : your_profile.LastName));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
You then use an extension method to IIdentity
to pull the information out of the claims identity:
public static ProfileName GetIdentityName(this IIdentity identity)
{
if (identity == null)
return null;
var first = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.GivenName),
var last = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.Surname)
return string.Format("{0} {1}", first, last).Trim();
}
internal static string FirstOrNull(this ClaimsIdentity identity, string claimType)
{
var val = identity.FindFirst(claimType);
return val == null ? null : val.Value;
}
Then, in your application (in your controller or view), you can just do:
var name = User.Identity.GetIdentityName();
User
is really just anIPrincipal
andIdentity
is justIIdentity
. You can easily create your own implementation ofUser
with it's own implementation ofIdentity
. They just need to adhere to the interfaces. – Hoarse