Ron*_*ald 3 c# asp.net asp.net-mvc asp.net-mvc-4
我使用下面的代码将文件流放入由 MVC 控制器返回的响应消息中。但是如何在客户端获取流?任何评论高度赞赏!谢谢!
服务器:
string filename = @"c:\test.zip";
FileStream fs = new FileStream(filename, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(fs);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
Run Code Online (Sandbox Code Playgroud)
如果您只是尝试下载二进制数据,则应该使用FileContentResult类型或FileStreamResult类型,可作为类File上的方法访问Controller。
这是一个简单的例子:
string filename = @"c:\test.zip";
var bytes = System.IO.File.ReadAllBytes(filename);
return File(bytes, "application/octet-stream", "whatevernameyouneed.zip");
Run Code Online (Sandbox Code Playgroud)
您可能想要添加代码以确保文件存在等。如果您很好奇,也可以在 MSDN 上阅读ReadAllBytes方法。
在您的 WebForms 项目中,您可以很容易地读取来自该控制器的响应:
var client = new HttpClient();
var response = await client.GetAsync("protocol://uri-for-your-MVC-project");
if(response.IsSuccessStatusCode)
{
// Do *one* of the following:
string content = await response.Content.ReadAsStringAsync();
// do something with the string
// ... or ...
var bytes = await response.Content.ReadAsByteArrayAsync();
// do something with byte array
// ... or ...
var stream = await response.Content.ReadAsStreamAsync();
// do something with the stream
}
Run Code Online (Sandbox Code Playgroud)
您阅读回复的方式由您决定;由于您还没有真正描述客户端站点应该如何处理您正在阅读的文件,因此很难更具体。
| 归档时间: |
|
| 查看次数: |
20013 次 |
| 最近记录: |