Geeks With Blogs
urig Tidbits from a .net life

I've stumbled upon behavior that I cannot understand in ASP.net's handling of the Response.Cookies object.

The trigger for this post is a page where I have Response.Flush() followed a bit later with an attempt to write an HttpCookie to the Response. Everything works fine when I try to write the cookie like so:

HttpContext.Current.Response.Cookies[name].Value = value;

But when I use this alternate method:

HttpCookie httpCookie = new HttpCookie(name, value);
HttpContext.Current.Response.Cookies.Set(httpCookie);

I get this exception thrown at me:

"Server cannot modify cookies after HTTP headers have been sent."

The unsettling part is that the second situation makes more sense to me than the first. Why? Because once Response.Flush() is called the HTTP headers have indeed been sent to the client and setting a cookie's value (which is done through HTTP Headers) should not be possible.

Why then is it okay to do this (set a cookie after HTTP Headers have been flushed to the client) if I'm using the indexer [] instead of the Set() method?

Your insight will be greatly appreciated :)

Posted on Sunday, March 4, 2007 5:42 PM | Back to top


Comments on this post: Response.Cookies.Set() vs. Response.Cookies[] =

# re: Response.Cookies.Set() vs. Response.Cookies[] =
Requesting Gravatar...
Maybe it's because in situation A, you're not changing the CookieCollection, but simply setting the value of an already existing cookie. In situation B, you're adding a brand new cookie to the collection...

I don't know if that's the actual reason, but it's the most significant difference between the two situations.
Left by Jannik Anker on Mar 05, 2007 4:16 PM

# re: Response.Cookies.Set() vs. Response.Cookies[] =
Requesting Gravatar...
HttpContext.Current.Response.Cookies[name].Value = value;
Actually the cookie is NOT written to client's computer. Although you can read this value in the following code
<% Response.Write(HttpContext.Current.Response.Cookies("abc").Value)%>

If you check the client's computer, it is NOT there.
Left by Ben on Jul 06, 2007 12:58 PM

Your comment:
 (will show your gravatar)


Copyright © urig | Powered by: GeeksWithBlogs.net