Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an asp.net mvc action to consistently deliver a file to the browser?

I'm building a little action to take an encrypted PDF file path, decrypt it, and deliver the resulting PDF to the browser.

My code works 100% of the time in Chrome and Firefox, but it works only 50% of the time in IE9.

When I follow the link in IE9, it looks like it opens the Adobe Reader plugin in the browser window, but no file is displayed until I hit refresh.

Here is my code:

    [CheckSubscriber]
    public ActionResult file(string path)
    {
        string mappedPath = Server.MapPath(
                                EncryptDecrypt.Decrypt(path,
                                EncString));

        return base.File(mappedPath, "application/pdf");

    }

How would I get this to work consistently in IE9?

I'm just thinking out loud here but maybe I am using the wrong mime-type?

like image 301
quakkels Avatar asked Jan 28 '26 13:01

quakkels


1 Answers

You should be explicitly setting

Content-Disposition: inline; filename="foo.pdf"

The content-disposition is a crucial response header when returning a response from the server. All browsers will correctly detect the file 100% of the time if this is specified along with the MIME type.

You can use Fiddler to ensure that the response headers are in order.

Edit

You cannot use the "ActionResult" return type for your action to do this.

You need to use "FilePathResult" or "FileStreamResult" both of which can be found in the System.Web.MVC namespace.

Alternatively you can create a Custom Action Return Type and use that for this action. The article I have provided gives step by step along with code as to how to go about doing this.

like image 192
vvohra87 Avatar answered Jan 30 '26 05:01

vvohra87