This project has moved. For the latest updates, please go here.

Server cannot append header after HTTP headers have been sent.

Mar 26, 2014 at 3:08 PM
I'm receiving following exceptions every once a while, but I can't reproduce this in my dev environment. Only observable on live machine, thoughts?
System.Web.HttpException (0x80004005): Server cannot append header after HTTP headers have been sent.
   at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
   at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
   at Microsoft.Owin.Infrastructure.OwinHelpers.AppendHeaderUnmodified(IDictionary`2 headers, String key, String[] values)
   at Microsoft.Owin.ResponseCookieCollection.Append(String key, String value, CookieOptions options)
   at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__b.MoveNext()
— End of stack trace from previous location where exception was thrown —
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__8.MoveNext()
— End of stack trace from previous location where exception was thrown —
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext()
— End of stack trace from previous location where exception was thrown —
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
— End of stack trace from previous location where exception was thrown —
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Coordinator
Mar 26, 2014 at 5:29 PM
Hmm. CookieAuth is trying to update headers (sign-in, sign-out, or refresh), but the response has already been sent. CookieAuth should have set the headers in OnSendingHeaders, triggered by the first write. However, in this case it is doing it on pipeline unwind because it never saw the write. The only reason OnSendingHeaders would not fire is if the response was being sent from a component not visible to the OWIN pipeline (aspx? native module?).

Do you know what component generated the response for these failed requests?
Mar 26, 2014 at 7:14 PM
This seems to happen only when the user is already authenticated. I'm not sure which module specifically because it happens pretty randomly for several different pages.

We do put in some tracking code in the cookie on page load if the user is authenticated, but we don't have any code inserting content into the response headers.
Coordinator
Mar 26, 2014 at 7:22 PM
It might be the sliding refresh. The cookie middleware will automatically renew/update cookies that have less than 50% of their expiration time remaining. See CookieAuthOptions.SlidingExpiration, ExpireTimeSpan.
Mar 26, 2014 at 9:22 PM
I see, but how come it throws an exception? What is the proper way of handling the cookie sliding refresh?

Can I configure its behaviour somehow?
Coordinator
Mar 26, 2014 at 10:15 PM
The real problem is not that the refresh is happening, but that the OWIN components don't know the response has been sent. So the question is, who is handling those responses?
Mar 27, 2014 at 1:10 AM
How would one check if a component has handled cookie sliding refresh?

I don't believe I have any other components handling the refresh, perhaps it is because I'm using UseExternalSignInCookie alongside with UseCookieAuthentication?
Coordinator
Mar 27, 2014 at 2:20 AM
Another component isn't handling the cookie refresh. The cookie refresh is happening on a random (time dependent) request. What's wrong is that the OWIN middleware doesn't see the response for this request, so it tries to do the refresh work too late, after the headers have been sent. What you need to identify is which resource was requested/served when this error happened. That will tell you which technology isn't meshing well with the OWIN middleware.
Mar 27, 2014 at 4:03 AM
I think I might be on to something, I noticed that in all the exception log, the cookie always contains the old auth cookie that we use prior switching to OWIN's cookie authentication. Do you think that might be throwing the exception? I'll need to create a test case before I can confirm this, but I think this might have been the cause.

Though I did have these setting in my web.config so maybe that's not it?
<authentication mode="None" />

<remove name="FormsAuthenticationModule" />
May 13, 2014 at 6:43 PM
I'm running into the same problem. One issue I found is that "FormsAuthenticationModule" is a misspelling in the VS template. It should be "FormsAuthentication". I have yet to set that in my own code so I don't know if that will solve this occasional and mysterious problem.
May 13, 2014 at 7:16 PM
Hi esassaman,

Thanks for the tip, I've corrected the module name according to your suggestion and verified the FormsAuthentication is no long listed in the Modules listing of the site.
However, the error still being logged on the site every once a while, so I don't think the configuration fixes this issue.
May 18, 2014 at 10:50 PM
I have had no luck with that as a fix either. It still happens to me on rare occasion as well. There are multiple places in my code where an .aspx file calls this type of code:

HttpContext.Current.response.StatusCode = 250;
HttpContext.Current.response.Flush();
HttpContext.Current.response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();

I do this type of thing typically in various .aspx files' code (that contains HTML markup) that needs to send a specific simple text response (usually an error message due to a caught exception) and not the HTML markup in the .aspx page. Now I wonder if that is bad practice when using OWIN components like the new Identity 2.0 stuff.

I tried setting ExpireTimeSpan to a much shorter value to see if I can get this exception to happen from the above code (or anywhere) and wasn't able to reproduce this exception. I still have no idea what is triggering it in my code. So as far as I can tell, calling the code above during any time during the expiration window causes no problem for me. So at least I know it's not consistently wrong :) Though I still wonder if CompleteRequest() is the culprit... I don't know which http pipeline event the Identity 2.0 stuff is hooking into, but if CompleteRequest is causing the skipping of a pipeline event that Identity 2.0 is expecting in order to set headers, that sure seems like the candidate. But then, why doesn't it happen every time the above code is called?
Coordinator
May 19, 2014 at 5:48 PM
Here's what I think is happening:
  1. A request arrives and enters the OWIN pipeline.
  2. The cookie middleware examines it and sees that here is a cookie present that's about to expire. It sets a flag to renew the cookie when the response is sent.
  3. No OWIN component handles the request so it falls through to ASP.NET (MVC, aspx, etc.).
  4. Some ASP.NET component handles the request and flushes out the response. Because this happens inside of ASP.NET, the OWIN components don't observe it, so the cookie middleware can't set the new cookie at this time.
  5. The request unwinds through the OWIN pipeline which thinks the request completed without sending headers, so it fires the OWIN OnSendingHeaders event. This triggers the cookie middleware to set the response header, which throws the exception shown above because the headers were already sent.
For Katana v2 the only workaround I'm aware of is to disable CookieAuthOptions.SlidingExpiration. You could also avoid flushing responses, but that's not always something you control.

For Katana v3 there are a few options:
A) There is a new OnException event for the cookie middleware that could catch and/or suppress the exception in ApplyResponseGrantAsync. This is primarily for debugging.
B) On .NET 4.5.2 we could hook a new API that should help us fire events in the correct order: http://msdn.microsoft.com/en-us/library/system.web.httpresponsebase.addonsendingheaders(v=vs.110).aspx. Filed as https://katanaproject.codeplex.com/workitem/263.

For Katana v4 / ASP.NET vNext this should be completely fixed because we've re-worked the pipeline to make sure middleware can better integrate with the ASP.NET components. E.g. we've fixed the problem in step 4 above where some components couldn't see the actions taken by others.
May 19, 2014 at 9:22 PM
I did some testing hoping to trigger the problem myself by setting ExpireTimeSpan to something like 30 seconds, then manually doing request after request after request, sometimes waiting 5 seconds after login, 10, 15, yadda yadda, hoping to force the problem to happen by sending requests roughly in and out of that time expiration window. It never happened. Every request ended with:

HttpContext.Current.response.Flush();
HttpContext.Current.response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();

I never do the above any more, but this is old code that has plenty of these type of "early exit points" littered all over the app. Before I knew any better, lol. I am running Identity 2.0.0 on Owin 2.1.0, on .net 4.5. I am just noticing nuget updates for Owin to 2.0.1 and Identity 2.0.1. I'm going to investigate and update right now.

So regarding AddOnSendingHeaders in .net 4.5.2 (which hopefully my hosting provider will upgrade too soon) how would I fix this problem using that? I've been trying to find some sample code on how that API works, to no avail.
Coordinator
May 19, 2014 at 9:59 PM
I don't expect Katana 2.0.1 or 2.1.0 to behave any differently.

There's nothing you can do with AddOnSendingHeaders, that's a change for me to make in Katana v3. It would fix step #4 above to notify the cookie middleware at the correct point for it to set the response header.

I was able to repro the issue with just the following code:
            app.Use((context, next) =>
            {
                context.Response.OnSendingHeaders(_ =>
                    context.Response.Headers["CustomHeader"] = "CustomValue",
                    null);
                return next();
            });

            app.Map("/Crash", subApp =>
                {
                    subApp.Run(context =>
                        {
                            HttpContext.Current.Response.StatusCode = 250;
                            HttpContext.Current.Response.Write("Goodbye World");
                            HttpContext.Current.Response.Flush();
                            HttpContext.Current.Response.SuppressContent = true;
                            HttpContext.Current.ApplicationInstance.CompleteRequest(); 
                            return Task.FromResult(0);
                        });
                });
Navigating to "/crash" should trigger an exception when setting the custom header.
Coordinator
May 21, 2014 at 10:07 PM
May 22, 2014 at 2:52 AM
Awesome thank for the help and insight. I was finally able to reproduce the problem on demand.

So I think the best way to handle this for now is to simply ignore this specific exception in Application_Error(). The only time that this is a problem is if it just so happens that someone is logged in when they cross the sliding refresh threshhold and it triggers the cookie expire date refresh which fails. So I kinda hate to just turn off the sliding window for everyone. No users see any problem since the response is already flushed to their browser by the time the exception happens. It looks like the only bad thing that happens is that thier cookie expiration date not get set further back, but I don't see a big problem with that since it's still good for a week (using the default 14 days). Chances are extremely high they will navigate to a "normal" .aspx page that does not manually flush/completeRequest which means the cookie expire will be successfully updated. So I think that will be my strategy for now.
Jun 2, 2014 at 4:45 PM
Tractcher,

Thanks for providing the patch, I tried taking the patch and applied it to build my own version of 2.1 compatible binary but the exception still seems to appear.
Coordinator
Jun 2, 2014 at 4:59 PM
FYI: I had to revert the fix because the new .NET 4.5.1 AddOnSendingHeaders API we were consuming did not work correctly. It sounds like we'll have to wait for 4.5.3.
Jul 17, 2014 at 12:40 PM
Hi Tratcher. Is there any update on this? Thanks.
Jul 31, 2014 at 3:51 AM
Hi,

@bluefoxreg @Tratcher

I'm having the same issue. I cannot reproduce in a dev environment (local). Issue is throwing only on my test server or live environment. In my case, the issue triggers on my Resource Application (Web API) where I used a custom FilterAttribute to handle authentication. Every time the context response of my API is set to 401, it throws an Error 500 on Elmah (only). Which is weird because the API responded perfectly including body content.

Any news? TIA.
This seems to happen only when the user is already authenticated.
I will try to take a look at this and see If setting identity to null of the Owin context will solve the issue.

Thanks.
Coordinator
Jul 31, 2014 at 3:59 AM
Are you using WebApi's OwinHost or WebHost package? This shouldn't be a problem for WebApi on the OwinHost.
Jul 31, 2014 at 12:11 PM
Edited Jul 31, 2014 at 12:14 PM
I'm not sure what you meant exactly by using. But here are the packages I have installed.
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net45" />
On Startup, I have these configured:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
...
config.SuppressDefaultHostAuthentication();
...
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
On the custom AuthorizationFilterAttribute (used per Action/Controller), I have an override method for OnAuthorization that sets actionContext.Response when authorization is invalid after the authentication. The codes when setting response are something like this:
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid authentication.");
The weird part is that the issue only happens when set to 401 and not when 403 or 400.

Is it allowed to set the HttpActionContext Response? Or I should set response in OwinContext?
Coordinator
Jul 31, 2014 at 2:15 PM
The request flow looks like this:
IIS->SystemWeb->OWIN->SystemWeb->WebApi

The problem is that SystemWeb doesn't reliably fire the events we need when components that run after us send the headers.

For WebApi you can work around this by switching from Microsoft.AspNet.WebApi.WebHost to Microsoft.AspNet.WebApi.Owin. Then you move your WebApi config into the Startup class like this:
https://aspnet.codeplex.com/SourceControl/latest#Samples/Katana/WebApi/Startup.cs

This makes your request flow look like this:
IIS->SystemWeb->OWIN->WebApi

Which keeps SystemWeb from getting in the way.
Aug 4, 2014 at 11:36 AM
Thanks Tratcher. Really helpful. I understand better now the flow and hosting Web API to Owin. I have moved all my Web API configurations to OwinHost and I don't get issues now with the request headers.

Now I face different dilemma and that is to make the Web API Help Page work. But I think it is out of scope to this discussion. Let me know for tips.

Thanks again.
Aug 14, 2014 at 6:06 AM
I too had this kind of issue while removing the cookies during signout. I just put the web api configuration inside the startup by calling app.UseWebApi(WebApiConfig.Configure(new HttpConfiguration));

This solved the issue for me. Thanks Tratcher
Aug 21, 2014 at 4:30 PM
Tratcher,

Any idea how to resolve this issue with the ASP .NET Identity Framework? I have posted this issue over there but so far no one has any recommendations:

https://aspnetidentity.codeplex.com/discussions/561617

It sounds like we want to make the request flow look like this:
IIS->SystemWeb->OWIN->WebApi

But not sure how to achieve that end result.
Coordinator
Aug 21, 2014 at 4:56 PM
MattOI, you need to initialize WebApi as shown in the sample linked above:
https://aspnet.codeplex.com/SourceControl/latest#Samples/Katana/WebApi/Startup.cs
Aug 21, 2014 at 5:08 PM
How does WebAPI have anything to do with ASP .NET Identity framework?

It's unclear to me how this alters the ASP .NET identity pipeline. Perhaps we are dealing with slightly different issues here, but the same error. Here is the stack trace (which differs from the original posters issue)
Exception information: 
    Exception type: HttpException 
    Exception message: Server cannot append header after HTTP headers have been sent.
   at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
   at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
   at Microsoft.Owin.Infrastructure.OwinHelpers.AppendHeaderUnmodified(IDictionary`2 headers, String key, String[] values)
   at Microsoft.Owin.ResponseCookieCollection.Append(String key, String value, CookieOptions options)
   at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware`2.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Coordinator
Aug 21, 2014 at 5:14 PM
You just referenced WebApi in your post, but I guess that was copied from my post above. Identity is not a stand-alone framework, what are you using it with? MVC?
Aug 21, 2014 at 5:15 PM
Webforms application. .NET 4.5.1...
Coordinator
Aug 21, 2014 at 5:21 PM
Ah. I'm not aware of any workarounds for Webforms or MVC, just WebApi. We're trying to get this fixed in Katana, but it's blocked on a bug in System.Web. See https://katanaproject.codeplex.com/workitem/263.
Aug 21, 2014 at 5:23 PM
Thanks so much for the response. I'll stop looking for a way to stop the flood of errors to our log management system until .NET 4.5.2 :-)
Sep 8, 2014 at 9:43 AM
Edited Sep 8, 2014 at 9:43 AM
I had this problem when I composed a new response in a Filter class. But the solution for me was to use the CreateResponse() Function of the HttpContext.

My first attempt that gave the error:
HttpResponseMessage resp = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
resp.Headers.Add("status", redirectmsg);
context.Response = resp;

My solution:
context.Response = context.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, redirectmsg);

// 'context' is an object from the type HttpContext or HttpActionContext, ...
Dec 3, 2014 at 6:10 PM
Any updates to this. Which .net framework will have this bug corrected?
Coordinator
Dec 3, 2014 at 6:18 PM
Dec 3, 2014 at 7:20 PM
Excellent! Thanks
Mar 13, 2015 at 9:39 AM
Try to use below code.

new RedirectResult(Constants.LoginUrl);

Thank you!! http://www.code-sample.com/
Jul 21, 2015 at 5:45 PM
So, despite https://katanaproject.codeplex.com/workitem/263 being closed as fixed, I'm still seeing this problem after moving my WebForms app that is using Katana 3.0.1 to the RTM release of .NET 4.6.
System.Web.HttpException (0x80004005): Server cannot append header after HTTP headers have been sent.
   at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
   at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
   at Microsoft.Owin.Infrastructure.ChunkingCookieManager.AppendResponseCookie(IOwinContext context, String key, String value, CookieOptions options)
   at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__f.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.<DoFinalWork>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Is there something else I need to do to prevent this from happening, or should this have been fixed by 3.0.1 and 4.6?
Jul 22, 2015 at 8:56 PM
:( I hope that is not true bording. I have been waiting a long time for this fix.

Did you update to the latest identity framework as well?
Jul 22, 2015 at 9:14 PM
My project doesn't use the Identity Framework stuff. I've directly integrated the Katana / Microsoft.Owin.Security.Cookies stuff into a legacy account system.

And I'm definitely still seeing the errors show up. I was looking forward to the final 4.6 RTM as well, hoping it would be gone.
Jul 22, 2015 at 9:22 PM
bording wrote:
My project doesn't use the Identity Framework stuff. I've directly integrated the Katana / Microsoft.Owin.Security.Cookies stuff into a legacy account system.

And I'm definitely still seeing the errors show up. I was looking forward to the final 4.6 RTM as well, hoping it would be gone.
Are you sure you recompiled with .NET 4.6 as the target framework?

Also note, that just switching your project to use .NET 4.6 is not sufficient when using the project settings pages on the solution.

You also to direct the config files to use the framework as well under the following configuration tags:

<system.web>
<compilation debug="true" targetFramework="4.6">
</compilation>
<httpRuntime targetFramework="4.6" />
</system.web>

Can you reconfirm that, and report back if that corrects the issue?
Jul 22, 2015 at 9:44 PM
Yes, I've definitely done all of those things, and I'm still seeing the error.
Oct 16, 2015 at 8:55 PM
I recently upgrade my web forms, web api project to use Identity. All newest versions, and framework 4.6. I get a similar error. Has anyone figured out what causes it?
[System.Web.HttpException: Server cannot append header after HTTP headers have been sent.]
   at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
   at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
   at Microsoft.Owin.Infrastructure.ChunkingCookieManager.AppendResponseCookie(IOwinContext context, String key, String value, CookieOptions options)
   at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__f.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware`2.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware`2.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware`2.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.<DoFinalWork>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
System.Web
Oct 28, 2015 at 1:01 AM
Edited Oct 28, 2015 at 1:04 AM
From what I can recall in my particular case, the only time that this is a problem is if it just so happens that someone is logged in when they cross the sliding refresh threshhold for their cookie and they wind up on a web forms page of mine that does a manual response flush and completeRequest() call, and in that situation when the cookie expire date refresh triggers, that causes the exception. You can turn off the sliding window for everyone as one possibility. But I didn't like that idea, and no users see any problem since the response is already flushed to their browser by the time the exception happens. It looks like the only bad thing that happens is that thier cookie expiration date does not get set further back, I didn't see that as a big problem for me since it's still good for a week (using the default 14 days). Chances are extremely high my users would later navigate to an .aspx page that does not manually do a response flush/completeRequest() which means the cookie expire will be successfully updated. So my workaround was to just ignore any exception with .Message=="Server cannot append header after HTTP headers have been sent." and I've had no problems since then. I will happily remove that hack once this bug is fixed but since then I have moved a lot of my site code to MVC and am not doing as many manual response flushing/competeRequest() calls in web forms pages.
Aug 14, 2016 at 3:56 PM
I have the same issue. i am using .net framework 4.6
and the following packages are installed
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.Security" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.Security.Cookies" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.Security.Facebook" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.Security.Google" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.Security.MicrosoftAccount" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.Security.OAuth" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.Security.Twitter" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net46" />
<package id="Owin" version="1.0" targetFramework="net46" />
<package id="Respond" version="1.2.0" targetFramework="net46" />

and when i logged in and left the website for long time like an hour and then refresh the page i get this error "Server cannot append header after HTTP headers have been sent," in the log database i am using log4net.

how to solve this problem
Sep 9, 2016 at 3:00 PM
Edited Sep 9, 2016 at 3:01 PM
This issue is a bug that the powers that be I guess have been ignoring for quite some time and it's frustrating and unacceptable. I am able to replicate this bug with a simple MVC web application that I setup to use OWIN. I narrowed it down to slidingexpiration being set to true and when the interval hits the error will fire and log in your event viewer. About a month ago I created a bug entry on connect.microsoft.com, posted the sample project with instructions on how to replicate the error and I haven't heard a peep from the original minion that was looking into the issue.

Check out the link I setup and posting your thoughts/feelings on this page are welcome. Maybe if enough people chime in we can get a response on this.

https://connect.microsoft.com/VisualStudio/Feedback/Details/3065110
Jan 4 at 10:23 PM
Tratcher, if WebHost is removed, how can Attribute Routing be configured?

This page mentioned needing to install Microsoft.AspNet.WebApi.WebHost
https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Thanks!