C# ASMX文件下载

C# ASMX文件下载,c#,.net,web-services,asmx,C#,.net,Web Services,Asmx,我有一个ASMX(无WCF)Web服务,其方法响应的文件如下所示: [WebMethod] public void GetFile(string filename) { var response = Context.Response; response.ContentType = "application/octet-stream"; response.AppendHeader("Content-Disposition", "attachment; filename="

我有一个ASMX(无WCF)Web服务,其方法响应的文件如下所示:

[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引用将此文件下载到本地文件系统。如何获取文件流


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

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

    <webServices>
        <protocols>
            <add name="HttpGet"/>
        </protocols>
    </webServices>
编辑:

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

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");
}

谢谢你的回答!是否有方法向WebClient实例提供cookie(如CookieContainer属性)?我使用cookies进行身份验证。
myCookieContainer = ... // your cookies

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