如何在ASP.NET Core中将对象存储在Cookie中。

huangapple go评论81阅读模式
英文:

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=/

如何在ASP.NET Core中将对象存储在Cookie中。

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 = &quot;TEST&quot;
    });

    var base64Data = Convert.ToBase64String(Encoding.UTF8.GetBytes(data));

    HttpContext.Response.Cookies.Append(&quot;dv-v3&quot;, base64Data);

    return Ok();
}

and then to retrieve the cookie string as a DeviceModel:

var base64Data = Request.Cookies[&quot;dv-v3&quot;];

var data = Encoding.UTF8.GetString(Convert.FromBase64String(base64Data));

var deviceModel = JsonConvert.DeserializeObject&lt;DeviceModel&gt;(data);

huangapple
  • 本文由 发表于 2023年7月24日 16:08:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752509.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定