【问题标题】:open generated pdf file in new tab instead of downloading..Web API在新选项卡中打开生成的 pdf 文件而不是下载..Web API
【发布时间】:2018-05-23 15:17:58
【问题描述】:

.Net 4.6.1 C#

我在运行时生成了一个pdf文件并且可以成功下载。我想在新选项卡中打开新创建的 pdf 文件,而不是下载它。这是我的代码(Web API 2.1 方法):

  public HttpResponseMessage ToPDF(string cn)
    {

        var stream = new MemoryStream();
            stream = GeneratePDF();


        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream.ToArray())
        };
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "file.pdf"
        };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");


        return result;


    }

我认为这会起作用,但事实并非如此。我的锚标签上也有 target="_blank" 。如何在新选项卡中打开新生成的 pdf 文件,而不是让浏览器将其下载到用户的硬盘上?谢谢

【问题讨论】:

  • 您需要将内容配置从附件更改为内联(顺便说一句,System.Net.Mime.DispositionTypeNames.Inline 有一个常量)。见iana.org/assignments/cont-disp/cont-disp.xhtml
  • @ckuri - 就是这样。请张贴作为答案,以便我可以给你适当的信用。谢谢
  • 按照您的建议,我将其发布为答案。
  • @BoundForGlory 你能告诉我,你是如何使用 target _blank 从浏览器调用这个 web api 的?

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


【解决方案1】:

除了 David Mkheyan 建议设置正确的 MIME 类型之外,您还需要将内容配置从 attachment 更改为 inline。

result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue(System.Net.Mime.DispositionTypeNames.Inline)
    {
        FileName = "file.pdf"
    };

根据https://www.iana.org/assignments/cont-disp/cont-disp.xhtmlattachment表示“用户控制显示”,inline表示“自动显示”。

【讨论】:

  • 很棒的工作伙伴!
  • 我仍然无法使用内联在新标签页中打开
【解决方案2】:

只需将媒体类型从 application/octet-stream 更改为 application/pdf 即可。我想您也可以将返回类型更改为 FileResult 而不是 HttpResponseMessage。 result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

【讨论】:

  • 感谢回复,但还是要下载pdf,不要在新标签页打开
【解决方案3】:

只需返回 PhysicalFileResult 并使用 HttpGet 方法,url 将打开 pdf 文件

public ActionResult GetPublicLink()
 {
         path = @"D:\Read\x.pdf";
        return new PhysicalFileResult(path, "application/pdf");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 2018-01-27
    • 2014-08-25
    • 2012-01-07
    • 2019-04-12
    相关资源
    最近更新 更多