Saturday, March 31, 2012

Strange behavior with HttpCookieCollection

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...

- Aadlaird@.earthlink.net wrote in
news:3f18afd7.184287250@.news.earthlink.net:

> 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.
----
C.R. Timmons Consulting, Inc.
http://www.crtimmonsinc.com/

0 comments:

Post a Comment