【问题标题】:Pdf corrupted in HttpResponseMessagePdf 在 HttpResponseMessage 中损坏
【发布时间】:2017-10-09 20:58:33
【问题描述】:

我有一个 ASP.NET MVC 5 项目,我正在尝试在其中下载 pdf。我认为这会非常简单,但显然不是这样,因为 pdf 在发送到浏览器时会以某种方式被错误地格式化。 Chrome 会读取 pdf,但所有特殊字符和图像看起来都已损坏,Edge 只是拒绝打开它。

pdf文件是用丹麦语编写的,所以它包含像'æ'、'ø'和'å'这样的字母,还包含各种图像。

我已经简化了我的代码当前代码,但问题仍然是一样的:

[HttpGet]
public HttpResponseMessage DownloadDocument()
{
    try
    {
        var localFilePath = "C:\\*somepath*\\Testpdf.pdf";
        var fileStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);
        fileStream.Seek(0, SeekOrigin.Begin);
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(fileStream);
        response.Content.Headers.Add("Content-Disposition", "inline;filename=\"Testpdf.pdf\"");
        response.Content.Headers.Add("Content-Length", fileStream.Length.ToString());
        response.Content.Headers.Add("Content-Name", "Testpdf.PDF");
        response.Content.Headers.Add("Content-Type", "application/pdf;charset=UTF-8");
        return response;
    }
    catch (Exception e)
    {
        throw e;
    }
}

它从磁盘读取 pdf 并将文件流分配给 HttpResponseMessage 的内容。在示例中,我使用的是 StreamContent,但如果切换到 ByteArrayContent,结果仍然相同。

我也尝试将文件写回磁盘,完全没有问题。我刚刚在 dotnetcore 2.0 Web 项目中做了同样的行为,没有任何问题,这让我相信 Web API 中的格式化程序解析内容错误。

我在我的智慧在这里结束,所以任何输入将不胜感激。

【问题讨论】:

  • 为什么将 content-type 设置为application/pdf;charset=UTF-8?您确定这是 PDF 中使用的字符集吗?
  • 我用这一行来检查它: var e = new StreamReader(fileStream).CurrentEncoding;这给出了“Unicode(UTF-8)”。只有编写 application/pdf 会产生相同的结果。

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


【解决方案1】:

我通过从请求标头中删除 jwt“授权”令牌来解决此问题。我将其更改为从 url 获取令牌,而是通过创建一个备用提供程序,遵循这篇文章: https://leastprivilege.com/2013/10/31/retrieving-bearer-tokens-from-alternative-locations-in-katanaowin/

【讨论】:

  • 这个答案与你原来的问题有什么关系?
猜你喜欢
  • 1970-01-01
  • 2016-08-20
  • 2022-01-14
  • 2013-01-04
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多