开发者

ASP.NET Response.TransmitFile() doesn't appear to be working

I 开发者_Go百科am calling a [WebMethod] with a piece of JQuery. The aim of the following code it to sent a recently zipped file to the user's browser. When the user clicks the 'Download' button, an AJAX request is sent to the ASP.NET page with is supposed to send the zip file.

Here is the code.

[WebMethod]
    public static void DownloadAlbum(string folderToDownload)
    {
        string archiveDir = "";

        ...some code...

        HttpContext.Current.Response.ContentType = "application/zip";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + path);
        HttpContext.Current.Response.TransmitFile(path);
        HttpContext.Current.Response.End();
    }

When this runs, nothing is sent to the browser, but no exceptions are thrown either. I'm unsure as to what is going on and why the file is not downloading.

The 'path' DEFINATELY has the correct address, and when the address of the file is hard-code the same happens.

Any help would be greatly appreciated!

Thanks,


When I transfer files via a web service, I usually do things a little differently. I'll not pretend this is the only way to do it, but it has worked for me in the past.

I prefer to retrieve documents using the HTTP GET verb, as follows:

[WebMethod()]
[ScriptMethod(UseHttpGet = true)]
public void DownloadAlbum(string folderToDownload)
{
    var path = // calculate and validate path...

    HttpContext.Current.Response.ContentType = "application/zip";
    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + path);
    HttpContext.Current.Response.TransmitFile(path);
    HttpContext.Current.Response.End();
}

Note that this method belongs to an .asmx service, and is not static.

In the web.config, I enable the service (Documents.asmx) for HttpGet as follows:

<location path="Documents.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
      </protocols>
    </webServices>
  </system.web>
</location>

With the service configured like so, the service can be called via a regular hyperlink without AJAX, from the application-relative URL ~/Documents.asmx/DownloadAlbum?folderToDownload=myfoldername.

Note that, to reduce the risk of CSRF attacks, you should avoid enabling HttpGet on a service that can update your system. I generally keep insert/update/delete methods in a separate service if I plan to GET-enable read methods.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜