Anemoia
Anemoia

Reputation: 8116

Force file download header

We're having a weird issue with offering a file on our ASP.NET server.

If the user clicks a link we want to have a file download dialog. No WMP opening for WMVs, no Adobe opening for PDFs, and so on.

To force this we use the following HTTP handler which jumps on WMVs, PDFs, and so on.

    public void ProcessRequest(HttpContext context)
    {
        // don't allow caching
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        context.Response.Cache.SetNoStore();
        context.Response.Cache.SetExpires(DateTime.MinValue);

        string contentDisposition = string.Format("attachment; filename=\"{0}\"", Path.GetFileName(context.Request.PhysicalPath));
        string contentLength;

        using (FileStream fileStream = File.OpenRead(context.Request.PhysicalPath))
        {
            contentLength = fileStream.Length.ToString(CultureInfo.InvariantCulture);
        }

        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("Content-Disposition", contentDisposition);
        context.Response.AddHeader("Content-Length", contentLength);
        context.Response.AddHeader("Content-Description", "File Transfer");
        context.Response.AddHeader("Content-Transfer-Encoding", "binary");
        context.Response.TransmitFile(context.Request.PhysicalPath);
    }

Sniffing with fiddler, these are the actual headers sent:

HTTP/1.1 200 OK
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Length: 8661299
Content-Type: application/octet-stream
Expires: -1
Server: Microsoft-IIS/7.5
Content-Disposition: attachment; filename="foo.wmv"
Content-Description: File Transfer
Content-Transfer-Encoding: binary
X-Powered-By: ASP.NET
Date: Wed, 04 Apr 2012 09:38:14 GMT

However this still opens WMP when we click on a WMV link, same for Adobe Reader, it still opens up Adobe Reader inside a IE Window.

This issue does not seem to be occurring on Firefox, however it occurs on IE8 (32-bit) on Windows 7 (32-bit).

Any help?

Upvotes: 4

Views: 10840

Answers (1)

huysentruitw
huysentruitw

Reputation: 28091

replace

context.Response.ContentType = "application/octet-stream";

with

context.Response.ContentType = "application/force-download";

and see what it does, don't know if it works for all browsers though.

Upvotes: 6

Related Questions