Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET, ASHX, "Server cannot append header after HTTP headers have been sent" after sending PDF Streem

Tags:

c#

asp.net

I visit my ASHX file, and it outputs a PDF perfectly. If I visit the very same ASHX with a different query string (I append DateTime.Now.Ticks to the end each visit), and I get this error:

Server cannot append hader after HTTP headers have been sent.

My code is below:

copy.CloseStream = false;
document.Close();

var r = context.Response;
r.ExpiresAbsolute = DateTime.Now;
r.BufferOutput = true;
r.ContentType = "application/pdf";
r.AppendHeader("Content-Type", r.ContentType);
r.AppendHeader("Content-disposition", "inline; filename=" + context.Server.UrlEncode(formType.File_Name));

r.BinaryWrite(copyStream.ToArray());
r.StatusCode = 200;
r.End();
originalReader.Close();
copy.CloseStream = true;
copy.Close();

There is no other place in this code that headers are sent. You are seeing the entire interaction with the Response object.

I've tried to use r.Flush(); and r.End(); I've also tried not sending them if they are already there, but this causes other issues.

like image 911
Matt Hudson Avatar asked Dec 07 '25 20:12

Matt Hudson


1 Answers

The problem is with r.StatusCode = 200;, which corresponds to setting the header's first line.

Since this occurs after sending payload, this is unacceptable in HTTP protocol.

You have to do that earlier.

like image 152
usr-local-ΕΨΗΕΛΩΝ Avatar answered Dec 10 '25 10:12

usr-local-ΕΨΗΕΛΩΝ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!