2014-05-13 16 views
6

Utworzono niestandardowy model użytkownika dla struktury podmiotu i tożsamości asp.net. Sprawdziłem inne odpowiedzi tutaj, są one blisko mojego pytania, ale odpowiedzi nie dotyczą mojego wymogu. więc proszę tutaj.Po tożsamości użytkownika niestandardowego, User.Identity.GetUserId() zwraca nieprawidłowy typ jako ciąg

Wszystko w porządku. Ale gdy próbuję uzyskać identyfikator użytkownika, takich jak:

ApplicationUser user = await manager.FindByIdAsync(User.Identity.GetUserId()); 

User.Identity.GetUserId() ciąg zwrotny. Skonfigurowałem to jak Guid. Ale zwraca ciąg :(

Moje zajęcia są tutaj. Proszę mi pomóc, jak mogę dostać User.Identity.GetUserId() w kontrolerze Web API GUID?

public class GuidUserLogin : IdentityUserLogin<Guid> 
    { 
    } 


    public class GuidUserRole : IdentityUserRole<Guid> 
    { 
    } 

    public class GuidUserClaim : IdentityUserClaim<Guid> 
    { 
    } 

    public class GuidRole : IdentityRole<Guid, GuidUserRole> 
    { 
    } 

//public class GuidUserContext : IdentityDbContext<ApplicationUser, GuidRole, Guid, GuidUserLogin, GuidUserRole, GuidUserClaim> { } 
    public class GuidUserStore : UserStore<ApplicationUser, GuidRole, Guid, GuidUserLogin, GuidUserRole, GuidUserClaim> 
    { 
     public GuidUserStore(DbContext context) 
      : base(context) 
     { 
     } 
    } 

    public class GuidRoleStore : RoleStore<GuidRole, Guid, GuidUserRole> 
    { 
     public GuidRoleStore(DbContext context) 
      : base(context) 
     { 
     } 
    } 


    public class ApplicationUser : IdentityUser<Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>, ICreateDateRequired 
    { 
     public ApplicationUser() 
     { 


     } 

     [Key] 
     public Guid UserId { get; set; } 

     public override Guid Id { get; set; } 

     public override string UserName { get; set; } 
     public string Name { get; set; } 
     public string Surname { get; set; } 

     public string Password { get; set; } 

     //Matching Attributes 

     public override string Email { get; set; } 
     public string FacebookId { get; set; } 
     public string TwitterId { get; set; } 
     public string GoogleId { get; set; } 
     public override string PhoneNumber { get; set; } 

     public string SocialAccessToken { get; set; } 

     public string Gender { get; set; } 

     public virtual List<Shade> Shades { get; set; } 

     [InverseProperty("ParentUser")] 
     public virtual List<UserFriendship> Friends { get; set; } 

     public virtual List<Contact> Contacts { get; set; } 

     //[Column(TypeName = "DateTime2")] 
     //[DatabaseGenerated(DatabaseGeneratedOption.Computed)] 
     public DateTime? CreateDate { get; set; } 

     public string ImageUrl { get; set; } 
     public string ThumbUrl { get; set; } 
     public string BackUrl { get; set; } 

     public virtual List<ContactDetail> UserContactDetails { get; set; } 
    } 

Odpowiedz

5

GetUserId() jest rzeczywiście Poniższa metoda rozszerzenie: (! ciasteczek)..

Microsoft.AspNet.Identity.IdentityExtensions.GetUserId(this IIdentity identity) 

W pewnym momencie nie ma sposobu, aby zapisać wartość jako Guid oznacza to, że trzeba zmienić ręcznie (I właśnie to zrobił sobie dzisiaj) Co Zrobiłem to wszystko, co używa Microsoft.AspNet.Identity, Microsoft.AspNet.Identity.Owin i Microsoft.Owin.Security w osobnym katalogu. Potem napisał moje własne klasy rozszerzenia:

internal static class IIdentityExtensions 
{ 
    public static Guid GetUserId(this IIdentity identity) 
    { 
     var result = Guid.Empty; 

     string id = Microsoft.AspNet.Identity.IdentityExtensions.GetUserId(identity); 

     Guid.TryParse(id, out result); 

     return result; 
    } 

    public static string GetUserName(this IIdentity identity) 
    { 
     string result = Microsoft.AspNet.Identity.IdentityExtensions.GetUserName(identity); 

     return result; 
    } 

    public static string FindFirstValue(this ClaimsIdentity identity, string claimType) 
    { 
     string result = Microsoft.AspNet.Identity.IdentityExtensions.FindFirstValue(identity, claimType); 

     return result; 
    } 
} 

Tylko upewnij się sprawdzić Guid.Empty (lub zmienić go na GUID?). Przekonasz się, że jest kilka rzeczy, które po prostu akceptują string i będziesz musiał je przekonwertować. Na przykład:

namespace Microsoft.Owin.Security 
{ 
    public static class AuthenticationManagerExtensions 
    { 
    public static ClaimsIdentity CreateTwoFactorRememberBrowserIdentity(
     this IAuthenticationManager manager, 
     string userId); 
    public static Task<bool> TwoFactorBrowserRememberedAsync(
     this IAuthenticationManager manager, 
     string userId); 
    } 
} 

Musisz mieć .GetUserId().ToString() dla niektórych metod działania.

+0

Ale gdy próbuję uzyskać identyfikator Guid w kontrolerze web api, zwraca ponownie ciąg znaków. var stringResult = IdentityExtensions.GetUserId (RequestContext.Principal.Identity); – Ras

+0

Wygląda na to, że problem z przestrzenią nazw jest nieprawidłowy. –

+0

Dzięki. Naprawiłem, jak powiedziałeś. A teraz daje błąd. Podczas generowania modelu wykryto jeden lub więcej błędów sprawdzania poprawności: GuidUserStore:: EntityType "GuidUserStore" nie ma zdefiniowanego klucza. Zdefiniuj klucz dla tego EntityType. UserStores: EntityType: EntitySet "UserStores" jest oparte na typie "GuidUserStore", który nie ma zdefiniowanych kluczy. – Ras

0

Do naszego projektu potrzebowałem abstrakcji klucza opartego na IUserKey (i zapisuję identyfikator jako long w tym interfejsie).

Problem z UserManager silnie uzależniony od ciągów został rozwiązany (dla mnie) po prostu przesłonięcie metody ToString() w konkretnej implementacji obiektu klucza użytkownika.

public class IdentityUserKey : IIdentityUserKey 
{ 
    public long UserId { get; set; } 

    public bool Equals(IIdentityUserKey other) 
    { 
     return other != null && other.UserId == UserId; 
    } 

    public override string ToString() 
    { 
     return UserId.ToString(); 
    } 
} 

W twoim przypadku, być może mógłby owinięty Guid w podobny interfejs, a następnie dostarczyła niezbędnego ToString() nadpisanie również.

9

Definicja GetUserId to:

public static string GetUserId(this IIdentity identity); 
public static T GetUserId<T>(this IIdentity identity) where T : IConvertible; 

Niestety Guid nie jest IConvertible i nie zwróci identyfikatora GUID typu w ogólnej formie. Dlatego nie możemy użyć: User.Identity.GetUserId()<Guid>, ponieważ niektóre osoby używają User.Identity.GetUserId()<Int>, gdy zmieniają identyfikator na Int.

Dlatego należy użyć Guid.Parse() lub Guid.TryParse()

Guid.Parse(User.Identity.GetUserId()) 

metoda @Erik działa dobrze, ale nie chciał, aby zastąpić oryginalny jeden, dodałem następujące ogólne rozszerzenia:

public static class ExtensionMethods 
{ 
    public static Guid ToGuid(this string value) 
    { 
     Guid result= Guid.Empty; 
     Guid.TryParse(value, out result); 
     return result;   
    } 
} 

a następnie użyłem tego:

User.Identity.GetUserId().ToGuid() 

Edytuj: Wymyśliłem inne rozwiązanie:

Dodałem rozszerzenie do obiektu tożsamości.

public static class IdentityExtensions 
{ 
    public static Guid GetGuidUserId(this IIdentity identity) 
    { 
     Guid result = Guid.Empty; 
     Guid.TryParse(identity.GetUserId(), out result); 
     return result; 
    } 
} 
Powiązane problemy