【问题标题】:PDF returned from Web API cannot be opened. There was an error opening this document. The file is damaged and could not be repaired从 Web API 返回的 PDF 无法打开。打开此文档时出错。文件已损坏,无法修复
【发布时间】:2019-04-26 16:30:15
【问题描述】:

我有一个返回 PDF 的 Web api 控制器。 Abobe Reader XI 11.0.12 无法打开某些 PDF

HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.BinaryWrite(myByteArray);
HttpContext.Current.Response.End();

以上代码可以正常运行,并且可以在 Adob​​e Reader 以及所有流行的浏览器中打开 PDF。

但它确实会抛出“发送 HTTP 标头后服务器无法设置状态”。我一直忽略但想解决,所以我实现了下面的代码。

HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.BinaryWrite(myByteArray);
HttpContext.Current.Response.Flush();

此代码也可以正常工作,但无法在 Adob​​e Reader XI 版本 11.0.12 中打开此代码返回的 PDF。 FF、Chrome、Edge 可以正常显示 PDF。 IE 11 不能。

打开此文档时出错。文件已损坏并且 无法修复。

【问题讨论】:

  • 如果一个浏览器可以读取该 PDF 而其他浏览器不能,那么您是在错误的地方寻找问题。这很可能是 PDF 内容的问题,而不是您将其发送到浏览器的方式。
  • 您能否提供有关 binaryObject 来自何处的代码?我没有看到这个变量在任何地方被初始化
  • 您需要在写入文件字节后结束响应。否则其他内容最终会被写入文件,从而损坏 PDF。无论如何,您为什么要直接写入 Web API 中的响应。不要那样做! Web API 有action results for returning files
  • 您可能会收到“发送 HTTP 标头后服务器无法设置状态”。因为您将标头写入响应,然后结束响应,从而导致异常,从而导致 Web API 尝试将 HTTP 状态代码设置为 500,从而导致额外的错误。所有这些都可以通过从您的操作方法中正确返回文件来避免。
  • 在 Web API 中,您不应写入响应。那不是你的工作。这就是框架的工作。因此,您代码中的所有HttpContext.Current.Response 调用都需要消失。相反,返回一个包含文件内容的操作结果。您可以轻松地进行网络搜索以了解如何在 Web API 中返回文件。

标签: c# asp.net-mvc pdf asp.net-web-api


【解决方案1】:

根据@mason 响应和链接Returning binary file from controller in ASP.NET Web API,我将所有HttpContext.Current.Response 替换为以下代码以解决此问题:

public HttpResponseMessage LoadPdf(int id)
{
    //get PDF in myByteArray

    //return PDF bytes as HttpResponseMessage
    HttpResponseMessage result = new HttpResponseMessage();
    Stream stream = new MemoryStream(myByteArray);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "my-doc.pdf" };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    result.StatusCode = HttpStatusCode.OK;
    return result;
}

【讨论】:

    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 2020-12-16
    • 1970-01-01
    相关资源
    最近更新 更多