ASMX文件下载

2xM*_*Max 3 .net c# 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Bro*_*ass 8

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

    <webServices>
        <protocols>
            <add name="HttpGet"/>
        </protocols>
    </webServices>
Run Code Online (Sandbox Code Playgroud)

然后你应该能够使用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");
Run Code Online (Sandbox Code Playgroud)

编辑:

要支持设置和检索cookie,您需要编写一个WebClient覆盖的自定义类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;
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用此自定义Web客户端,您可以:

myCookieContainer = ... // your cookies

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