HttpResponseMessage返回ByteArrayContent结果 - 以chrome格式预览文档

时间:2016-06-19 11:10:36

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

我正在尝试在Chrome中预览文件,但它会继续下载。

    [HttpGet]
    [ResponseType(typeof(ByteArrayContent))]
    public HttpResponseMessage Download([FromUri] int uploadId)
    {
        try
        {
            Upload upload = UploadController.LoadByPrimaryKey(uploadId);

            var path = upload.FullPath + "\\" + upload.UploadGuid + upload.Extension;
            var mimeType = MimeTypeMap.GetMimeType(upload.Extension);

            MemoryStream pdf = new MemoryStream(File.ReadAllBytes(path));
            HttpResponseMessage result = null;
            result = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(pdf.ToArray());
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
            result.Content.Headers.ContentDisposition.FileName = upload.OriginalFileName;
            result.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);

            return result;
        }
        catch (Exception ex)
        {
          //..
        }
    }

这是来自Fiddler的踪迹。

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 793708
Content-Type: application/pdf
Expires: -1
Server: Microsoft-IIS/10.0
Access-Control-Allow-Origin: http://localhost:6701
Access-Control-Allow-Credentials: true
Content-Disposition: inline; filename="1451048-Customer Acceptance.pdf"
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 19 Jun 2016 10:52:35 GMT
...

我见过Open PDF file in browser rather than downloading pdf fileHow to force files to open in browser instead of download (pdf)?,但我仍遇到问题。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我认为您的代码没有任何问题,它看起来更像是您的浏览器设置问题(尽管大多数浏览器都有默认设置来呈现PDF)。

如果在Mozilla中尝试

  1. 单击菜单按钮,然后选择选项。
  2. 选择“应用程序”面板。
  3. 在列表中查找可移植文档格式(PDF),然后单击它以将其选中。
  4. 单击上述条目的“操作”列中的下拉箭头,然后选择“在Firefox中预览”。
  5. 参考 - https://support.mozilla.org/en-US/kb/disable-built-pdf-viewer-and-use-another-viewer

    适用于Chrome

    1. 转到“选项”(单击右上角的扳手按钮)
    2. 转到:引擎盖下 - >内容设置 - >插件
    3. 点击“管理个人插件......
    4. 找到Adobe Acrobat插件(或任何其他PDF查看器)并确保已启用
    5. 我的API中有完全相同的代码,它允许我根据ContentDispositionHeaderValue渲染PDF或下载(内联渲染和附件下载)

      请参阅以下我服务器的响应标题

      HTTP/1.1 200 OK
      Cache-Control: private
      Content-Length: 46270
      Content-Type: application/pdf
      Server: Microsoft-IIS/10.0
      Content-Disposition: inline; filename=Sample.pdf
      X-AspNet-Version: 4.0.30319
      X-Powered-By: ASP.NET
      Date: Mon, 20 Jun 2016 03:38:39 GMT
      

      希望这有帮助