英文:
How to store object in cookie in asp.net core
问题
{
"g": "TEST",
"platform": null
}
英文:
I've a class that I want save in response cookie.
public IActionResult Get()
{
var data = JsonConvert.SerializeObject(new DeviceModel
{
Group = "TEST"
});
HttpContext.Response.Cookies.Append("dv-v3", data);
return Ok();
}
public class DeviceModel
{
[JsonProperty(PropertyName = "g")]
public string Group { get; set; }
[JsonProperty(PropertyName = "platform")]
public string Platform { get; set; }
}
But, encoded value is saved in cookie.
dv-v3=%7B%22g%22%3A%22TEST%22%2C%22platform%22%3Anull%7D; path=/
I want to cookie value be like this:
{"g":"TEST","platform":null}
How can I do this in asp.net core?
答案1
得分: 1
短答案:你不能
Cookies 对可以包含的字符有限制。例如,大括号和引号都不是可接受的字符。1, 2
另一个选项:
你可以将原始序列化数据进行如下编码:
public IActionResult Get()
{
var data = JsonConvert.SerializeObject(new DeviceModel
{
Group = "TEST"
});
var base64Data = Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
HttpContext.Response.Cookies.Append("dv-v3", base64Data);
return Ok();
}
然后将 cookie 字符串作为 DeviceModel 检索:
var base64Data = Request.Cookies["dv-v3"];
var data = Encoding.UTF8.GetString(Convert.FromBase64String(base64Data));
var deviceModel = JsonConvert.DeserializeObject<DeviceModel>(data);
英文:
Short answer: You can't
Cookies have constraints on the characters that can be included. For example, braces and quotes are not acceptable characters. 1, 2
Another option:
You could encode the original serialized data as follows:
public IActionResult Get()
{
var data = JsonConvert.SerializeObject(new DeviceModel
{
Group = "TEST"
});
var base64Data = Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
HttpContext.Response.Cookies.Append("dv-v3", base64Data);
return Ok();
}
and then to retrieve the cookie string as a DeviceModel:
var base64Data = Request.Cookies["dv-v3"];
var data = Encoding.UTF8.GetString(Convert.FromBase64String(base64Data));
var deviceModel = JsonConvert.DeserializeObject<DeviceModel>(data);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论