Strange behavior with HttpCookieCollection

  • Thread starter Thread starter adlaird
  • Start date Start date
A

adlaird

Hi,

I created a simple webform, put a test button on it and implemented a
click handler that looks like so:

private void btnTest_Click(object sender, System.EventArgs e)
{
HttpCookieCollection oCookReq =
HttpContext.Current.Request.Cookies;
HttpCookieCollection oCookResp =
HttpContext.Current.Response.Cookies;

int n1 = oCookReq.Count;
int n2 = oCookResp.Count;
bool bIsNull = (oCookResp["someCookieName"] == null);
int n3 = oCookReq.Count;
int n4 = oCookResp.Count;

Response.Write(string.Format("Before: Request = {0}, Response
= {1}<br>", n1, n2));
Response.Write(string.Format("After: Request = {0}, Response
= {1}<br>", n3, n4));
}


When I click the button the test output on the page is:

Before: Request = 1, Response = 0
After: Request = 2, Response = 1

Can anyone explain why the mere act of looking for a cookie in the
response collection would cause one to get added to both the response
and request collections? I tried the test again using a new
HttpCookieCollection (i.e. not one from the current context) and do
not get this behavior. Clues?

Thanks much...

- A
 
(e-mail address removed) wrote in
Hi,

I created a simple webform, put a test button on it and
implemented a click handler that looks like so:

private void btnTest_Click(object sender, System.EventArgs e)
{
HttpCookieCollection oCookReq =
HttpContext.Current.Request.Cookies;
HttpCookieCollection oCookResp =
HttpContext.Current.Response.Cookies;

int n1 = oCookReq.Count;
int n2 = oCookResp.Count;
bool bIsNull = (oCookResp["someCookieName"] == null);
int n3 = oCookReq.Count;
int n4 = oCookResp.Count;

Response.Write(string.Format("Before: Request = {0},
Response
= {1}<br>", n1, n2));
Response.Write(string.Format("After: Request = {0},
Response
= {1}<br>", n3, n4));
}


When I click the button the test output on the page is:

Before: Request = 1, Response = 0
After: Request = 2, Response = 1

Can anyone explain why the mere act of looking for a cookie in
the response collection would cause one to get added to both the
response and request collections? I tried the test again using
a new HttpCookieCollection (i.e. not one from the current
context) and do not get this behavior. Clues?

You've stumbled upon a frustrating (and, AFAIK, undocumented) aspect
of the ASP.NET cookies response collection. Simply querying the
collection will create the cookie if it doesn't exist.

Here's an article that explains this in more depth:

http://www.codeproject.com/aspnet/AspNetCookies.asp

Hope this helps.

Chris.
 
Back
Top