ASP.NET MVC:如何让浏览器打开并显示PDF而不是显示下载提示?

Luc*_*Sam 40 pdf asp.net-mvc

好的,所以我有一个生成PDF并将其返回给浏览器的动作方法.问题是,IE不会自动打开PDF,而是显示下载提示,即使它知道它是什么类型的文件.Chrome做同样的事情.在这两种浏览器中,如果我单击指向存储在服务器上的PDF文件的链接,它将打开正常,并且永远不会显示下载提示.

以下是调用以返回PDF的代码:

public FileResult Report(int id)
{
    var customer = customersRepository.GetCustomer(id);
    if (customer != null)
    {
        return File(RenderPDF(this.ControllerContext, "~/Views/Forms/Report.aspx", customer), "application/pdf", "Report - Customer # " + id.ToString() + ".pdf");
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

这是服务器的响应头:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Thu, 16 Sep 2010 06:14:13 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 2.0
Content-Disposition: attachment; filename="Report - Customer # 60.pdf"
Cache-Control: private, s-maxage=0
Content-Type: application/pdf
Content-Length: 79244
Connection: Close
Run Code Online (Sandbox Code Playgroud)

我是否必须在响应中添加一些特殊内容才能让浏览器自动打开PDF?

任何帮助是极大的赞赏!谢谢!

Dar*_*rov 58

Response.AppendHeader("Content-Disposition", "inline; filename=foo.pdf");
return File(...
Run Code Online (Sandbox Code Playgroud)

  • @wilk,不要将文件名保留在File(...)的调用中 (13认同)
  • 这会返回重复的Content-Disposition标头,Chrome会拒绝该文件.有没有办法使用File方法,但返回内联文件没有重复标题? (7认同)
  • 以为我会添加 - 强制下载开关"内联;" 成为"依恋". (2认同)

Mar*_*len 17

在HTTP级别,您的"内容处置"标题应具有"内联"而非"附件".不幸的是,FileResult(或它的派生类)不直接支持它.

如果您已经在页面或处理程序中生成文档,则只需将浏览器重定向到那里即可.如果这不是您想要的,您可以继承FileResult并添加对内联流文档的支持.

public class CustomFileResult : FileContentResult
   {
      public CustomFileResult( byte[] fileContents, string contentType ) : base( fileContents, contentType )
      {
      }

      public bool Inline { get; set; }

      public override void ExecuteResult( ControllerContext context )
      {
         if( context == null )
         {
            throw new ArgumentNullException( "context" );
         }
         HttpResponseBase response = context.HttpContext.Response;
         response.ContentType = ContentType;
         if( !string.IsNullOrEmpty( FileDownloadName ) )
         {
            string str = new ContentDisposition { FileName = this.FileDownloadName, Inline = Inline }.ToString();
            context.HttpContext.Response.AddHeader( "Content-Disposition", str );
         }
         WriteFile( response );
      }
   }
Run Code Online (Sandbox Code Playgroud)

更简单的解决方案是不在方法上指定文件名Controller.File.这样您就不会获得ContentDisposition标头,这意味着您在保存PDF时会丢失文件名提示.