Server cannot modify cookies after HTTP headers have been sent

16,075

Solution 1

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.

Solution 2

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.

Share:
16,075
amateur
Author by

amateur

Updated on June 27, 2022

Comments

  • amateur
    amateur almost 2 years

    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?