3
votes

I am using cookies in one of my ASP.NET Core MVC (.NET Framework) applications. I am trying to keep an object value while the client browser session is alive. I want to read, write and update that value.

I order to serialize and deserialize my object I use the JavascriptSerializer class from System.Web.Script.Serialization namespace and in order to handle the cookie I am using the HttpResponse and HttpRequest classes from the Microsoft.ASPNetCore.Http namespace.

I can read the cookie then deserialize it to my object or Serialize my object then write it to the cookie. But I cannot update the cookie because of the Response.Cookies object not allowing me to update an existing cookie. Then I deleted the cookie and append it to the Response.Cookies object, that worked but. Is there any other way of updating a cookie within an MVC6 application without having to deleted it?. That is not "cookie updating"!!

2

2 Answers

5
votes

Cookies cannot be updated. Nor, for that matter can they be deleted. This is not an issue with MVC, it's a fact about cookies, see e.g. https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies : the only operation the server can do on a cookie is to set it. Perhaps it is helpful to think of the cookie as owned by the browser not the server.

  • To update a cookie, you overwrite it with a new value.
  • To delete a cookie, you set the expiration to yesterday.

in the browser you can see that re-appending a new value for the cookie has the effect you want: the browser gets the new value. e.g.

serverside:

HttpContext.Response.Cookies.Append("key", "value set at " + DateTime.Now.TimeOfDay);

and client side:

document.writeln(document.cookie);
console.log("document.cookie", document.cookie);
-1
votes

Try this: CookieManager Wrapper (https://github.com/nemi-chand/CookieManager) .

it helps you to read/write/update the http cookie in asp.net core. it has fluent API's to ease of use