开发者

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

I'm building a little action to ta开发者_开发技巧ke 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?


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.


I would use Fiddler to see the difference between the request/response that the browsers send/receive and see if you can spot it from there.


Here's how I return an Excel file (pdf should be the same):

    public FileResult DownloadErrors(string filename)
    {
        var file = System.IO.File.ReadAllText(filename);

        return File(new System.Text.UTF8Encoding().GetBytes(file), "application/ms-excel", "Errors.csv");
    }

Be sure to use FileResult instead of ActionResult.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜