Csharp/C#教程:ASP.Net MVC:如何读取我的自定义声明值分享


ASP.Net MVC:如何读取我的自定义声明值

请参阅以下代码。 我知道这样我们可以将自定义数据添加到声明中,但现在的问题是如何读回这些值。 说我想读回索赔的价值电子邮件和电子邮件2请告诉我需要写什么代码来回读索赔电子邮件和电子邮件2的值。

UserManager userManager = new UserManager(new UserStore(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)); 

您可以使用ClaimsIdentity上的FindFirst(string type)方法根据声明类型检索声明。 在这种情况下, EmailEmail2

 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 = "https://schemas.mycompany.com/identity/claims/email"; public const string Email2 = "https://schemas.mycompany.com/identity/claims/email2"; } } } 

然后创建扩展方法以从ClaimsIdentity实现中提取它们,前提是它是从ClaimsIdentity派生的。

上述就是C#学习教程:ASP.Net MVC:如何读取我的自定义声明值分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public static class GenericIdentityExtensions { ///  /// Return the Email claim ///  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; } ///  /// Return the Email2 claim ///  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; } ///  /// Retrieves the first claim that is matched by the specified type if it exists, String.Empty otherwise. ///  internal static string FindFirstOrEmpty(this ClaimsIdentity identity, string claimType) { var claim = identity.FindFirst(claimType); return claim == null ? string.Empty : claim.Value; } } 

www.ctvol.com true Article Csharp/C#教程:ASP.Net MVC:如何读取我的自定义声明值分享

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1019562.html

(0)
上一篇 2022年1月4日 下午9:22
下一篇 2022年1月4日 下午9:22

精彩推荐