Server cannot add header after sending HTTP headers C # pdf inline

So, I had this problem for a while, trying to return the inline answer in PDF format. I searched all the help pages for answers to them and cannot find something that works. I made a simplified example of what I am doing below. But the core is just like real production. This question does not always occur, but it annoys him when he does it. It almost looks like some kind of weird moment or something else that I don’t see is happening.

I get this error System.Web.HttpException (0x80004005): File not found ---> System.Web.HttpException (0x80004005): the server cannot add the header after sending the HTTP headers.

Does anyone know how to fix this?

[HttpGet] public ActionResult PDF(string id, bool inline = false) { try { MemoryStream PDFStream = GetPdfStream(id); PDFStream.Position = 0; string PDFFile = "Test.pdf"; if (inline) { Response.AppendHeader("Content-Disposition", string.Format("inline; filename={0}", PDFFile)); Response.BufferOutput = true; return File(PDFStream, MediaTypeNames.Application.Pdf); } else return File(PDFStream, MediaTypeNames.Application.Pdf, PDFFile); } catch (Exception Ex) { throw new HttpException(404, "File Not Found", Ex); } } 
+4
source share
1 answer

You must clear the header first before adding new ones.

 if (inline) { Response.ClearHeaders(); Response.AppendHeader("Content-Disposition", string.Format("inline; filename={0}", PDFFile)); Response.BufferOutput = true; return File(PDFStream, MediaTypeNames.Application.Pdf); } else return File(PDFStream, MediaTypeNames.Application.Pdf, PDFFile); 
+2
source

All Articles