ASMX文件下载 [英] ASMX file download

查看:140
本文介绍了ASMX文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an ASMX(no WCF) webservice with a method that responses a file that looks like:

[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参考将该文件下载到本地文件系统.如何获取文件流?

and I want to download this file to local filesystem using web reference in my console application. How to get the filestream?

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

P.S. I tried download files via post request(using HttpWebRequest class) but I think there is much more elegant solution.

推荐答案

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

You can enable HTTP in the web.config of your web service.

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

然后,您应该仅可以使用Web客户端下载文件(经过文本文件测试):

Then you should be able to just use a web client to download the file (tested with text file):

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 类,很容易做到,只需几行代码:

To support setting and retrieving cookies you need to write a custom WebClient class that overrides GetWebRequest(), it's easy to do and just a few lines of code:

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客户端,请执行以下操作:

To use this custom web client you would do:

myCookieContainer = ... // your cookies

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

这篇关于ASMX文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆