Open PDF result in browser tab with MVC 3

2019-02-08 18:03发布

问题:

I am using ASP.NET MVC 3. I have a controller action that returns a PDF file like this:

Public Class ReportController
    ...
    Function Generate(id As Integer) As ActionResult
        ...
        Return File(output, "application/pdf", "something.pdf")
        ' "output" is a memory stream
    End Function

The code works but Firefox doesn't display the result in a tab, the result is either downloaded or opened with Adobe Reader.

I know that Firefox can display PDF in a tab because I can just google some PDF, click the link, and the PDF will open in a tab.

How do I set up the action so the PDF will open in a tab?

回答1:

I got the answer from the related links on the right:

Response.AppendHeader("Content-Disposition", "inline")
Return File(output, "application/pdf")

The PDF opens in a tab, but the filename hint is lost, even if I do it like this:

Response.AppendHeader("Content-Disposition", "inline; filename=something.pdf")
Return File(output, "application/pdf", "something.pdf")

So finally I didn't bother to give filename hint at all.

EDIT

ASP.NET MVC 3's File with 3 parameters:

Return File(output, "application/pdf", "something.pdf")

will add Content-Disposition: attachment; filename="something.pdf" to the response header, even if there is already a Content-Disposition in the response header.

So if you manually added Content-Disposition to the header, and then use File with 3 parameters, you end up with two Content-Disposition headers. Firefox 8 will say that the response is corrupted if the response header is like this.

So best way to do it now is add Content-Disposition manually for 'inline', and then use File with 2 parameters:

Response.AppendHeader("Content-Disposition", "inline; filename=something.pdf")
Return File(output, "application/pdf")


回答2:

This is configurable in your browser. You can change the settings to download / open in browser or open in relevant application in tools->options->applications section for all file types. Thi has nothing to do with your code.



回答3:

Try linking directly to the PDF.... If it opens in a tab then try changing your route to end with .pdf