3

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 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

you now also have a delete method on HttpContext.Response.Cookies which makes deleting cookies easier
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.