Strange behavior with HttpCookieCollection

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
 
C

Chris R. Timmons

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top