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=" + 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 引用将此文件下载到本地文件系统。如何获取文件流?
PS 我尝试通过发布请求(使用 HttpWebRequest 类)下载文件,但我认为还有更优雅的解决方案。
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();
}
}
}
and I want to download this file to local filesystem using web reference in my console application. How to get the filestream?
P.S. I tried download files via post request(using HttpWebRequest class) but I think there is much more elegant solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在 Web 服务的 web.config 中启用 HTTP。
然后您应该能够仅使用 Web 客户端下载该文件(使用文本文件进行测试):
编辑:
要支持设置和检索 cookie,您需要编写自定义
WebClient
重写GetWebRequest()< 的类/code>,这很容易做到,只需几行代码:
要使用此自定义 Web 客户端,您需要执行以下操作:
You can enable HTTP in the web.config of your web service.
Then you should be able to just use a web client to download the file (tested with text file):
Edit:
To support setting and retrieving cookies you need to write a custom
WebClient
class that overridesGetWebRequest()
, it's easy to do and just a few lines of code:To use this custom web client you would do: