Created
May 24, 2016 23:13
-
-
Save jburditt/7961f415b1b39df36182465b85f6950a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Security.Claims; | |
using Newtonsoft.Json; | |
namespace Account | |
{ | |
public static class ClaimsExtensions | |
{ | |
public static string Get(this ClaimsIdentity identity, string type) | |
{ | |
return identity.Claims.FirstOrDefault(p => p.Type == type)?.Value; | |
} | |
public static T Get<T>(this ClaimsIdentity identity, string type) where T : new() | |
{ | |
var json = identity.Claims.FirstOrDefault(p => p.Type == type)?.Value; | |
return json == null ? new T() : JsonConvert.DeserializeObject<T>(json); | |
} | |
public static void Set(this ClaimsIdentity identity, string type, string value) | |
{ | |
identity.AddClaim(new Claim(type, value)); | |
} | |
public static void Set<T>(this ClaimsIdentity identity, string type, T obj) | |
{ | |
var json = JsonConvert.SerializeObject(obj); | |
identity.AddClaim(new Claim(type, json)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment