.Net在Cookie中存取Json数据

Cookie是以键值对的形式来保存数据的,但有时我们想保存多个数据到一个cookie中去,这是我们就需要用到Json,如何在Cookie中存取Json数据就是我们今天要解决的问题

假设需要向Cookie中存入三个变量的值:

string data1 = "a";
string data2 = "b";
int data3 = 1;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

//Json写入Cookie
var jsonData = ModelToJson(new { data1 , data2 , data3  });
WriteCookie("JsonData", jsonData );

//从Cookie中读取Json
var cookieValue = ReadCookie("JsonData");
var data= (JObject)JsonConvert.DeserializeObject(cookieValue);
if(data != null)
{
    var data1= JsonValue("data1 ", "", data);
    var data2= JsonValue("data2 ", "", data);
    var data3= JsonValue("data3 ", "", data);
}
//上面调用的方法
public static string ModelToJson(object model)
{
    try
    {
        return JsonConvert.SerializeObject(model).ToString();
    }
    catch
    {
         return "";
    }
}

public static string JsonValue(string key, string returnValue, JObject item)
{
    if (item.Property(key) == null || item[key].ToString() == "")
        return returnValue;
    else
         return item[key].ToString();
}

public static bool WriteCookie(string strName, string strValue,int days=1)
{
    if (string.IsNullOrEmpty(strName))
            return false;
    HttpCookie cookie = new HttpCookie(strName);
    cookie.Value = strValue;
    cookie.Expires = DateTime.Now.AddDays(days);
    cookie.HttpOnly = true;
    HttpContext.Current.Response.Cookies.Add(cookie);
    return true;
}

public static string ReadCookie(string strName)
{
    if (HttpContext.Current.Request.Cookies != null
        && HttpContext.Current.Request.Cookies[strName] != null)
    {
        return HttpContext.Current.Request.Cookies[strName].Value;
    }
    else
        return "";
}

你可能感兴趣的:(.Net在Cookie中存取Json数据)