代码之家  ›  专栏  ›  技术社区  ›  Eedoh

为什么我的PDF文档不能在ASP.NET MVC2中呈现/下载?

  •  0
  • Eedoh  · 技术社区  · 15 年前

    我在开发中有一个ASP.NET MVC2应用程序,在呈现 .pdf 来自生产服务器的文件。

    在我的Visual Studio 2010集成开发服务器上,一切工作正常,但在我将应用程序发布到生产服务器之后,它就中断了。它不会抛出任何异常或任何类型的错误,它只是不显示文件。

    以下是显示PDF文档的功能:

    public static void PrintExt(byte[] FileToShow, String TempFileName, 
                                                           String Extension)
    {
        String ReportPath = Path.GetTempFileName() + '.' + Extension;
    
        BinaryWriter bwriter = 
            new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
        bwriter.Write(FileToShow);
        bwriter.Close();
    
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo.FileName = ReportPath;
        p.StartInfo.UseShellExecute = true;
        p.Start();
    }
    

    我的生产服务器正在运行Windows Server 2008和IIS 7。

    3 回复  |  直到 15 年前
        1
  •  4
  •   Darin Dimitrov    15 年前

    您不能期望在服务器上打开与PDF文件浏览相关联的默认程序。尝试将文件返回到响应流中,该响应流将在客户端计算机上有效地打开文件:

    public ActionResult ShowPdf()
    {
        byte[] fileToShow = FetchPdfFile();
        return File(fileToShow, "application/pdf", "report.pdf");
    }
    

    现在导航到 /somecontroller/showPdf . 如果要在浏览器中打开PDF而不显示下载对话框,可以尝试在返回之前将以下内容添加到控制器操作中:

    Response.AddHeader("Content-Disposition", "attachment; filename=report.pdf");
    
        2
  •  2
  •   marc.d    15 年前

    我建议您使用ASP.NET MVC FileResult类来显示PDF。

    看见 http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx

    您的代码在Web服务器上打开了PDF。

        3
  •  0
  •   Eedoh    15 年前

    我就是这样做的。

    public ActionResult PrintPDF(byte[] FileToShow, String TempFileName, String Extension)
        {
            String ReportPath = Path.GetTempFileName() + '.' + Extension;
    
            BinaryWriter bwriter = new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
            bwriter.Write(FileToShow);
            bwriter.Close();
    
            return base.File(FileToShow, "application/pdf");
        }
    

    谢谢大家的努力。我使用的解决方案与达林的方案最相似(几乎相同,但他的方案更漂亮:d),所以我接受他的方案。

    投票给你们所有人(包括答案和评论)

    谢谢