C#从Cookie读取无效的JSON基元

本文关键字:JSON 基元 无效 读取 Cookie | 更新日期: 2023-09-27 18:22:49

我使用JQuery.Cookie将javascript对象存储为Cookie值:

    var refinerData = {};
// Read in the current cookie if it exists:
if ($.cookie('RefinerData') != null) {
    refinerData = JSON.parse($.cookie('RefinerData'));
}
// Set new values based on the category and filter passed in
switch(category)
{
    case "topic":
        refinerData.Topic = filterVal;
        break;
    case "class":
        refinerData.ClassName = filterVal;
        break;
    case "loc":
        refinerData.Location = filterVal;
        break;
}    
// Save the cookie:
$.cookie('RefinerData', JSON.stringify(refinerData), { expires: 1, path: '/' });

当我在firebug中调试时,cookie值的格式似乎正确:

{"主题":"疾病预防和管理","地点":"哈奇里山诊所","课程名称":"我患有糖尿病,我能吃什么?"}

我正在用C#编写一个SharePoint web部件,它读取cookie并对其进行解析:

        protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies["RefinerData"];
        if (cookie != null)
        {
            string val = cookie.Value;
            // Deserialize JSON cookie:
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var refiners = serializer.Deserialize<Refiners>(cookie.Value);
           output.AppendLine("Deserialized Topic = " + refiners.Topic);
            output.AppendLine("Cookie exists: " + val);
        }
    }

我有一个Refiners类,用于序列化到:

    public class Refiners
{
    public string Topic { get; set; }
    public string ClassName { get; set; }
    public string Location { get; set; }
}   

然而,这段代码抛出了一个"无效的JSON原语"错误。我不明白为什么这不起作用。一种可能是它没有正确读取cookie。当我把cookie的值打印成字符串时,我得到:

%7B%22主题%22%3A%22疾病%20预防%20和%20管理%22%2C%22类别%22%3A/22分娩%20%26%20育儿%202013%22%2C/22地点%22%3A22GHC%20East%20诊所%22%7D

C#从Cookie读取无效的JSON基元

显示URL编码,尝试使用HtmlUtilityUrlDecode方法解码值(其中实例由页面通过Server属性公开):

var refiners = serializer.Deserialize<Refiners>(Server.UrlDecode(cookie.Value));

我认为您需要在反序列化之前解码cookie。尝试使用;

Refiners refiners = serializer.Deserialize<Refiners>(Server.UrlDecode(cookie.Value));