ASMX文件下载

时间:2011-01-24 21:01:50

标签: c# .net web-services asmx

我有一个ASMX(没有WCF)webservice,其方法可以响应一个看起来像这样的文件:

[WebMethod]
public void GetFile(string filename)
{
    var response = Context.Response;
    response.ContentType = "application/octet-stream";
    response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    using (FileStream fs = new FileStream(Path.Combine(HttpContext.Current.Server.MapPath("~/"), fileName), FileMode.Open))
    {
        Byte[] buffer = new Byte[256];
        Int32 readed = 0;

        while ((readed = fs.Read(buffer, 0, buffer.Length)) > 0)
        {
            response.OutputStream.Write(buffer, 0, readed);
            response.Flush();
        }
    }
}

我想在我的控制台应用程序中使用Web引用将此文件下载到本地文件系统。如何获取文件流?

P.S。我尝试通过post请求下载文件(使用HttpWebRequest类),但我认为有更优雅的解决方案。

1 个答案:

答案 0 :(得分:8)

您可以在Web服务的web.config中启用HTTP。

    <webServices>
        <protocols>
            <add name="HttpGet"/>
        </protocols>
    </webServices>

然后您应该能够使用Web客户端下载文件(使用文本文件测试):

string fileName = "bar.txt"
string url = "http://localhost/Foo.asmx/GetFile?filename="+fileName;
using(WebClient wc = new WebClient())
wc.DownloadFile(url, @"C:\bar.txt");

修改:

要支持设置和检索Cookie,您需要编写一个覆盖GetWebRequest()的自定义WebClient类,这很容易做,只需几行代码:

public class CookieMonsterWebClient : WebClient
{
    public CookieContainer Cookies { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
        request.CookieContainer = Cookies;
        return request;
    }
}

要使用此自定义Web客户端,您可以执行以下操作:

myCookieContainer = ... // your cookies

using(CookieMonsterWebClient wc = new CookieMonsterWebClient())
{
    wc.Cookies = myCookieContainer; //yum yum
    wc.DownloadFile(url, @"C:\bar.txt");
}