C# 在CHROME中不完全打开PDF 我试图在Chrome中打开一个PDF文件,但是在显示过程中它似乎被卡在了某个地方。这段代码似乎可以工作,因为它可以在IE中打开PDF,但不知道为什么它会卡在chrome中。屏幕将灰显,显示装载标志,并在7/8停止。该文件大约为6MB或更大 public static void ReturnPDF(byte[] contents) { var response = HttpContext.Current.Response; response.Clear(); response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf"); response.BufferOutput = true; response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf; response.BinaryWrite(contents); response.Flush(); response.Close(); response.End(); }

C# 在CHROME中不完全打开PDF 我试图在Chrome中打开一个PDF文件,但是在显示过程中它似乎被卡在了某个地方。这段代码似乎可以工作,因为它可以在IE中打开PDF,但不知道为什么它会卡在chrome中。屏幕将灰显,显示装载标志,并在7/8停止。该文件大约为6MB或更大 public static void ReturnPDF(byte[] contents) { var response = HttpContext.Current.Response; response.Clear(); response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf"); response.BufferOutput = true; response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf; response.BinaryWrite(contents); response.Flush(); response.Close(); response.End(); },c#,google-chrome,pdf,C#,Google Chrome,Pdf,有什么想法吗?谢谢 [更新] 我试用了30.0版的firefox,效果不错。我的IE是8.0.7601.17514,它也可以打开pdf。我的Chrome是39.0.2171.95。不确定浏览器的版本是否重要,这里只有chrome无法打开内嵌PDF [已解决] 添加内容长度后,chrome可以打开内嵌PDF public static void ReturnPDF(byte[] contents) { var response = HttpContext.Curren

有什么想法吗?谢谢

[更新]

我试用了30.0版的firefox,效果不错。我的IE是8.0.7601.17514,它也可以打开pdf。我的Chrome是39.0.2171.95。不确定浏览器的版本是否重要,这里只有chrome无法打开内嵌PDF

[已解决]

添加内容长度后,chrome可以打开内嵌PDF

   public static void ReturnPDF(byte[] contents)
    {
        var response = HttpContext.Current.Response;

        response.Clear();
        response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf");

        //After adding Content-Length, chrome is able to open PDF inline
        response.AppendHeader("Content-Length", contents.Length.ToString());

        response.BufferOutput = true;
        response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
        response.BinaryWrite(contents);

        response.Flush();
        response.Close();

        response.End();
    }

尝试使用内容配置:附件标题。

谢谢mkl的建议


我在标题中添加了内容长度,pdf可以在Chrome中成功打开

OP的原始代码创建了如下响应:

response.Clear();
response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf");
response.BufferOutput = true;
response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
response.BinaryWrite(contents);
response.End();
此代码尤其不设置内容长度标题。一些Web浏览器版本不仅包括Chrome,而且还有其他版本的其他浏览器,如果没有该头,往往会过早地考虑下载完成。

如果既没有提供非身份传输编码,也没有提供内容长度,那么在最初创建为持久连接的连接上检测下载何时完成可能不是件小事

因此,这里的解决方案是添加

response.AppendHeader("Content-Length", contents.Length.ToString());

在写入内容之前。

不在标题中传输内容长度。有些观众不喜欢这样。@mkl你说得对。在我添加了内容长度后,chrome最终可以毫无问题地打开。Thanks@mkl你能把你的答案贴在下面吗?这样我就可以给你学分了。谢谢你把答案编辑成你的问题。如果问题本质上仍然是一个包含背景的问题,而你的答案包含了解决方案,那就更好了。如果你愿意,我可以回答。@mkl,谢谢你的建议。我做了相应的更改,请在下面留下您的答案。谢谢,这将强制下载pdf。我想让它在浏览器中强制打开,所以我使用了内联。它可以在IE中打开pdf,但在打开时被chrome卡住了