0

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

enter image description here

I want to cookie value be like this:

{"g":"TEST","platform":null}

How can I do this in asp.net core?

Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41

1 Answers1

1

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);
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
Neil W
  • 7,670
  • 3
  • 28
  • 41