gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:16:19 25 4
gpt4 key购买 nike

我正在使用 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":"Disease Prevention and Management","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

最佳答案

出现 URL 编码,尝试使用 UrlDecode 解码值HtmlUtility 的方法(其中一个实例由页面通过 Server 属性公开):

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

关于C# 从 Cookie 读取无效的 JSON 基元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17707446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com