【问题标题】:C# Invalid JSON Primitive Reading from CookieC# 从 Cookie 读取无效的 JSON 原语
【发布时间】:2013-07-16 10:59:42
【问题描述】:

我正在使用 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值的值似乎格式正确:

{"Topic":"疾病预防与管理","Location":"Hatchery Hill Clinic","ClassName":"我有糖尿病,吃什么?"}

我正在用 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%22Topic%22%3A%22Disease%20Prevention%20and%20Management%22%2C%22Class%22%3A%22Childbirth%20%26%20Parenting%202013%22%2C%22Location%22%3A% 22GHC%20East%20Clinic%22%7D

【问题讨论】:

    标签: c# json sharepoint-2013


    【解决方案1】:

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

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

    【讨论】:

    • 好的,谢谢!那行得通。我不得不稍作调整才能访问 Server.UrlDecode,因为它是一个 Share Point webpart,但它工作得很好: var refiners = serializer.Deserialize(HttpContext.Current.Server.UrlDecode(cookie.Value));跨度>
    • @user1231748 当然,我应该为您提供访问静态引用的详细信息,我的错。很高兴你成功了。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      相关资源
      最近更新 更多