Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to update cookies in asp.net mvc

I can write and read cookies but I can't change value for existing cookie it always has first set value. I found few ways how it can be implemented but no one works. Here is my code:

private void AddPost(string key)
    {
        var context = System.Web.HttpContext.Current;
        var request = context.Request;
        var response = context.Response;

        var cookie = request.Cookies[Constants.PostsViewing];

        if (cookie == null || string.IsNullOrEmpty(cookie.Value))
        {
            response.Cookies.Add(new HttpCookie(Constants.PostsViewing, key)
            {
                Expires = DateTime.Now.AddDays(365)
            });
        }
        else
        {
            if (cookie.Value.Split(';').Contains(key))
            {
                return;
            }

            var v = cookie.Value + ";" + key;

            cookie.Value = v;
            cookie.Expires = DateTime.Now.AddDays(365);
            response.Cookies.Add(cookie);

            // this way also doesn't work
            //cookie.Value = v;
            //response.AppendCookie(cookie);

            // and this
            //response.Cookies[Constants.PostsViewing].Value = v;
            //response.Cookies[Constants.PostsViewing].Expires = DateTime.Now.AddDays(365);
        }

    }

According to msdn cookie file should be owerwritten.

Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten.

Do you have any idea how to fix it?

like image 828
mykhailovskyi Avatar asked Sep 06 '14 15:09

mykhailovskyi


3 Answers

I just ran into this exact scenario with a similar block of code:

public ActionResult Index(int requestValue)
{
    var name = "testCookie";
    var oldVal = Request.Cookies[name] != null ? Request.Cookies[name].Value : null;
    var val = (!String.IsNullOrWhiteSpace(oldVal) ? oldVal + ";" : null) + requestValue.ToString();

    var cookie = new HttpCookie(name, val)
    {
        HttpOnly = false,
        Secure = false,
        Expires = DateTime.Now.AddHours(1)
    };

    HttpContext.Response.Cookies.Set(cookie);

    return Content("Cookie set.");
}

The first time that code would run, the cookie would be set without incident. But any subsequent run would never update it at all (value or expiration).

Turns out, the semi-colon is an illegal character in a cookie value, and trying to delimit your values with it will cause the cookie value to be truncated. If we change the semi-colon to another character, like a pipe (|), everything works out just fine.

Consider the header sent for a cookie value (courtesy of Fiddler):

Response sent 61 bytes of Cookie data:

Set-Cookie: testCookie=2;1; expires=Tue, 09-Sep-2014 19:23:43 GMT; path=/

As we can see, the semi-colon is being used to separate the individual parts of the cookie definition. Thus, if you want to use a semi-colon in cookie value itself, it must be encoded so as not to be misinterpreted. This answer gives a more detailed look into the actual specification: https://stackoverflow.com/a/1969339/143327.

like image 98
Nathan Taylor Avatar answered Nov 15 '22 11:11

Nathan Taylor


You can't use a semi-colon, in plain text, as your delimiter.

According to the ancient Netscape cookie_spec:

This string is a sequence of characters excluding semi-colon, comma and white space.

like image 4
Jeff Odle Avatar answered Nov 15 '22 11:11

Jeff Odle


You can't directly modify a cookie. Instead you are creating a new cookie to overrite the old one. http://msdn.microsoft.com/en-us/library/vstudio/ms178194(v=vs.100).aspx

Try

var v = cookie.Value + ";" + key;

Response.Cookies[Constants.PostsViewing].Value = v;
Response.Cookies[Constants.PostsViewing].Expires = DateTime.Now.AddDays(365);

This should change the client Response instead of the servers Request.

In order to use Response.AppendCookie, you first have to get a HttpCookie from your Cookies collection.

like image 1
chconger Avatar answered Nov 15 '22 13:11

chconger