示例#1
0
 /// <summary>
 /// Create identity from a cookie data
 /// </summary>
 /// <param name="cookieString">String stored in cookie, created via ToJson method</param>
 /// <returns>Instance of identity</returns>
 public static ICustomIdentity FromJson(string cookieString)
 {
     try
     {
         if (string.IsNullOrEmpty(cookieString))
         {
             return(null);
         }
         IdentityRepresentation serializedIdentity = null;
         using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(cookieString)))
         {
             DataContractJsonSerializer jsonSerializer =
                 new DataContractJsonSerializer(typeof(IdentityRepresentation));
             serializedIdentity = jsonSerializer.ReadObject(stream) as IdentityRepresentation;
         }
         CustomIdentity identity = new CustomIdentity()
         {
             IsAuthenticated = serializedIdentity.IsAuthenticated,
             Name            = serializedIdentity.Name,
             Roles           = serializedIdentity.Roles
                               .Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries),
             Id = serializedIdentity.ID
         };
         return(identity);
     }
     catch
     {
         return(null);
     }
 }
示例#2
0
        /// <summary>
        /// Create serialized string for storing in a cookie
        /// </summary>
        /// <returns>String representation of identity</returns>
        public string ToJson()
        {
            string returnValue = string.Empty;
            IdentityRepresentation representation = new IdentityRepresentation()
            {
                IsAuthenticated = this.IsAuthenticated,
                Name            = this.Name,
                Roles           = string.Join("|", this.Roles),
                ID = this.Id
            };

            DataContractJsonSerializer jsonSerializer =
                new DataContractJsonSerializer(typeof(IdentityRepresentation));

            using (MemoryStream stream = new MemoryStream())
            {
                jsonSerializer.WriteObject(stream, representation);
                stream.Flush();
                byte[] json = stream.ToArray();
                returnValue = Encoding.UTF8.GetString(json, 0, json.Length);
            }

            return(returnValue);
        }