简体   繁体   中英

How to read multiple cookie with same name in webapi using C#

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);
                }
            }               
        };

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM