5

We have two cookies created with same name. When i am iterating through loop, i am always getting first cookie. Is there way to access both cookie separately?

        if (Request.Cookies.AllKeys.Where(x => x == "test").Count() > 1)
        {
            foreach (var cookie in Request.Cookies.AllKeys)
            {
                if (Request.Cookies[cookie].Name == "test")
                {
                    var temp = System.Web.HttpContext.Current.Request.Cookies["test"];
                    temp.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(temp);
                }
            }               
        };
PANKAJ
  • 153
  • 1
  • 8
  • By default, you will get the cookies that are set against the domain where you have hosted the web api. if that's not required, then you would be required to have a wild card domain for the cookies like `*.company.com` – Saravanan Aug 01 '17 at 19:21

2 Answers2

4

When a cookie already exists, and you update it (through the response's Cookies collection), either by adding or updating it, a second 'duplicate' cookie is added to the Request's Cookies collection. This duplicate one is actually the one you just updated.

Although I did not check this on MSDN documentation, I believe this is most probably by design. Why you ask? Because it allows you to get either YOUR current version of the cookie (the one you've just updated/added through the Response), or the one that was actually sent over by the user's browser (which is thus their current version of the cookie at this moment in time).

Now, using either Cookies.Get(name), Cookies[name] or -the way you are doing it- looping through the key collection (from the start) and then returning the first match, will always result in the first cookie beïng returned. This is the cookie as the user still knows it, thus not the one you've been updating during this request.

If you want to retrieve 'your' current version of the cookie, you must get the last one with that name, instead of the first. You can do so like this:

int index = Array.LastIndexOf(this.HttpRequest.Cookies.AllKeys, cookieKey);

if (index != -1)
{
    result = this.HttpRequest.Cookies[index];
}

Of course this will also always return the correct cookie if you didn't update it within the current request.

Kornelis
  • 101
  • 1
  • 5
0

we cannot have two cookies with the same name in a particular domain and also by default we get the cookies from the current domain. So I am not seeing a case where to you can get two cookies with the same name in the above-mentioned code.

Please mention your issue wit more detail.

Pavan k
  • 48
  • 10
  • 2
    You have a cookie in your domain and a cookie with the same name in your subdomain. They appear both in the request, but with different domain. The more strict will you read, but some cases you might need to access the other one. – Norbert Kardos Sep 16 '20 at 10:42