5

In pageload, if you do Response.Cookies.Add(..., immediately in the next line, you can access that cookie via Request.Cookies(...

I know that under the covers, the cookie is added to Request.Cookies by .net, but the original request never had that cookie.

If what I'm saying is correct, why is it this way? Shouldn't the cookie be available in the following request? Shouldn't the immediate access to Request.Cookies(... be null?

Steve
  • 5,802
  • 12
  • 54
  • 76

1 Answers1

6

You're right, ASP.NET does do that behind the scenes:

After you add a cookie by using the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client.

-- HttpRequest.Cookies page on MSDN

Why is it like that? At a guess, it's because that's how developers expect it to work.

Powerlord
  • 87,612
  • 17
  • 125
  • 175
  • As a side note, this is a somewhat common complaint about PHP... that using `setcookie` doesn't add said cookie to the `$_COOKIE` global. – Powerlord Aug 04 '10 at 17:09
  • 1
    Actually this has been driving me crazy. I needed to expire a cookie and add a new cookie but this behaviour meant I was expiring not only the old cookie but also the new one. And no I don't think it's a fair comment to suggest developers expect it to work that way. I'm a developer and I try to avoid side-effects when I'm writing code. But yes, the link to the documentation was invaluable, thank you. – David Clarke May 16 '12 at 04:30