簡體   English   中英

發送HTTP標頭后,服務器無法附加標頭c#pdf內聯

[英]Server cannot append header after HTTP headers have been sent c# pdf inline

因此,由於嘗試返回pdf內聯響應,我已經遇到了一段時間了。 我在幫助編碼頁中搜索了所有內容,以找到答案,但是找不到可行的方法。 我在下面做了一個簡化的例子。 但是核心與實際生產完全相同。 這個問題並非總是會發生,但是在發生時卻很煩人。 這幾乎就像是一個奇怪的計時問題,或者我沒有看到的其他事情正在發生。

我收到此錯誤System.Web.HttpException(0x80004005):找不到文件---> System.Web.HttpException(0x80004005):發送HTTP標頭后,服務器無法附加標頭。

有誰知道如何解決這一問題??

    [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);
        }
    }

您必須先清除標題,然后再添加新標題

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM