Jeśli używasz Asp.Net tożsamość, to jest bardzo łatwe do zrobienia z roszczeniami.
W swojej metodzie SignInAsync
(lub gdziekolwiek jesteś tworzeniu tożsamości roszczeń), dodać typy wniosków GivenName
i Surname
:
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);
}
wtedy użyć metodę rozszerzenia do IIdentity
wyciągnąć informacje out of the roszczenia tożsamość:
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;
}
Następnie w aplikacji (w kontroler lub widoku), można po prostu zrobić:
var name = User.Identity.GetIdentityName();
Jak rozumiem, masz inną tabelę z dodatkowymi danymi użytkownika. I chcesz pobrać dane bieżącego użytkownika. Czy mam rację? Czy korzystasz z Entity Framework? A w jaki sposób wolisz przechowywać te dane w innej tabeli? –
"Użytkownik" to tak naprawdę tylko "IPrincipal", a "Tożsamość" to po prostu "IIdentity". Możesz łatwo stworzyć własną implementację 'User' z własną implementacją' Identity'. Muszą tylko przestrzegać interfejsów. – TyCobb
Od kiedy używasz Asp.Net Identity, sposobem na to jest Roszczenie. Zobacz moją odpowiedź zamieszczoną poniżej. –