3

I am creating a web application in C#.

When my page loads I fire an asynchronous thread to process some data. Part of this processing is the updating of a cookie. However when I save the cookie to the response by

System.Web.HttpContext.Current.Response.Cookies.Add(cookie), I get the following exception:

HttpException: Server cannot modify cookies after HTTP headers have been sent.

Any way I can work around or fix this?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
amateur
  • 43,371
  • 65
  • 192
  • 320

3 Answers3

4

Unless you have a very good reason to, you shouldn't be spinning up background worker threads in an ASP.NET request. Ultimately you still have to wait for this thread to finish its work before you send the response back to the browser.

It sounds like the response stream has already been partially written to and then your thread is trying to add the cookie.

I'd rethink your strategy here and take a read of the following guidelines:

Chapter 6 — Improving ASP.NET Performance - Threading Guidelines

It looks like a dated document but the principles still stand. If the reason for making your call to the data processor is to prevent the ASP.NET worker thread from blocking and using up resources because the data processor is long running, then consider making the page an Asynchronous page instead.

Kev
  • 118,037
  • 53
  • 300
  • 385
  • "It sounds like the response stream has already been partially written to and then your thread is trying to add the cookie." - yes correct. Is this possible? – amateur Mar 31 '11 at 23:36
  • @Niall - yes that's possible, but without seeing exactly how you're structuring the code I wouldn't speculate where. – Kev Mar 31 '11 at 23:38
1

Yes, Cookies are part of the http response and in a async operation you cannot change anything after response is generated and sent to browser.

To workaround this i recommend to build a ajax loop on browser to get async operation result. When operation completed you can return a cookie with ajax response.

ertan
  • 645
  • 1
  • 7
  • 14
0

What if it is in preinit or init? not sure if this will help though. http://msdn.microsoft.com/en-us/library/ms178472.aspx#lifecycle_events

m4tt1mus
  • 1,642
  • 14
  • 24
  • I also have this error occuring in the Init event of the page. But Page:Init is before Application:PreSendRequestHeaders (see http://chiranjeevinooli.blogspot.co.at/2009/05/application-page-and-control-events-in.html). What could be going wrong here? – Krisztián Balla Jun 24 '15 at 08:52