在新选项卡中打开生成的 pdf 文件而不是下载..Web API

2024-01-07

.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 文件,而不是通过浏览器将其下载到用户的硬盘上?谢谢


除了 David Mkheyan 提出的设置正确的 MIME 类型的建议之外,您还需要更改内容配置attachment to 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.xhtml https://www.iana.org/assignments/cont-disp/cont-disp.xhtml attachment表示“用户控制的显示”并且inline是“自动显示”。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在新选项卡中打开生成的 pdf 文件而不是下载..Web API 的相关文章