views:

22

answers:

1

I want to store a cookie using something like

Response.Cookies.Set(new HttpCookie("name","value");

after I have finished the page lifecycle, so it makes sense to put it in the OnUnload() event.

However at this stage, Request and Response have already been unloaded, so throw a null ref exception.

Has anybody got any brain storms to get around this?

All i can think of is putting it in OnPreRender(), but am worried this may be too 'soon'.

+1  A: 

As the cookies are sent in the HTTP header, you have to set the cookie before anything is written to the response stream. Thus, you have to set the cookie before the page is rendered, as that is what's generating the code that is sent in the response.

So, adding a cookie after the page life cycle is way too late. Why do you think that it makes any difference when you add the cookie to the page anyway? As cookies are sent in the HTTP header, they will arrive to the browser at the same time regardless of when you run the code to add them.

Guffa
It makes a difference because the value i want to set in the cookie may change, during the lifecycle. I.e. Some time after Page_Load has finished.
maxp
If the value that you want to store in the cookie is changed by a control event in the page (e.g. a button click), then Page_PreRender will work fine as it runs after all control events.
Guffa