2016-09-21 5 views
2

см. Ниже код. я узнал, что таким образом мы можем добавить наши пользовательские данные к претензиям, но теперь вопрос заключается в том, как считывать эти значения. говорят, я хочу прочитать обратно значение для претензий Email и EMAIL2 скажите, пожалуйста, какой код я должен написать считаны значение для претензий Email и EMAIL2 благодаряASP.Net MVC: Как прочитать значение моих пользовательских требований

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext())); 
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie 
var user = userManager.Find(userName, password); 
identity.AddClaim(new Claim("Email", user.Email)); 
identity.AddClaim(new Claim("Email2", user.Email)); 

ответ

3

Вы можете использовать метод FindFirst(string type) на ClaimsIdentity для получения претензии на основе типа претензии. В этом случае Email или Email2

var claimType = "Email"; 
var claim = identity.FindFirst(claimType); 
var email = claim == null ? string.Empty : claim.Value; 

я обычно хранить типы претензий констант

public static partial class Constants { 
    public class Security { 
     public static class ClaimTypes { 
      public const string Email = "http://schemas.mycompany.com/identity/claims/email"; 
      public const string Email2 = "http://schemas.mycompany.com/identity/claims/email2"; 
     } 
    } 
} 

, а затем создать методы расширения для извлечения их из IIdentity реализации при условии, что происходит от ClaimsIdentity.

public static class GenericIdentityExtensions { 
    /// <summary> 
    /// Return the Email claim 
    /// </summary> 
    public static string GetEmail(this IIdentity identity) { 
     if (identity != null && identity.IsAuthenticated) { 
      ClaimsIdentity claimsIdentity = identity as ClaimsIdentity; 
      if (claimsIdentity != null) 
       return claimsIdentity.FindFirstOrEmpty(Constants.Security.ClaimTypes.Email); 
     } 
     return string.Empty; 
    } 
    /// <summary> 
    /// Return the Email2 claim 
    /// </summary> 
    public static string GetEmail2(this IIdentity identity) { 
     if (identity != null && identity.IsAuthenticated) { 
      ClaimsIdentity claimsIdentity = identity as ClaimsIdentity; 
      if (claimsIdentity != null) 
       return claimsIdentity.FindFirstOrEmpty(Constants.Security.ClaimTypes.Email2); 
     } 
     return string.Empty; 
    } 
    /// <summary> 
    /// Retrieves the first claim that is matched by the specified type if it exists, String.Empty otherwise. 
    /// </summary> 
    internal static string FindFirstOrEmpty(this ClaimsIdentity identity, string claimType) { 
     var claim = identity.FindFirst(claimType); 
     return claim == null ? string.Empty : claim.Value; 
    } 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^