如何在IHttpActionResult操作,Web API控制器中实现以下功能?
我是否需要将HttpResponseBase
修改为其他内容?
public void ZipFilesToResponse(HttpResponseBase response, IEnumerable<Asset> files, string zipFileName)
{
using (var zipOutputStream = new ZipOutputStream(response.OutputStream))
{
zipOutputStream.SetLevel(0); // 0 - store only to 9 - means best compression
response.BufferOutput = false;
response.AddHeader("Content-Disposition", "attachment; filename=" + zipFileName);
response.ContentType = "application/octet-stream";
foreach (var file in files)
{
var entry = new ZipEntry(file.FilenameSlug())
{
DateTime = DateTime.Now,
Size = file.Filesize
};
zipOutputStream.PutNextEntry(entry);
storageService.ReadToStream(file, zipOutputStream);
response.Flush();
if (!response.IsClientConnected)
{
break;
}
}
zipOutputStream.Finish();
zipOutputStream.Close();
}
response.End();
}
在这里使用:
[HttpPost]
[Route("DownloadFiles/{company_id}")]
public IHttpActionResult DownloadFiles(Int64 company_id, TasksFilterModel searchModel)
{
var files = .....;
ZipFilesToResponse(_______,files,"download.zip");
return ????
}
答案 0 :(得分:1)
您当前的public class MyController : Controller
{
[HttpPost]
[Route("DownloadFiles/{company_id}")]
public void DownloadFiles(Int64 company_id, TasksFilterModel searchModel)
{
var files = ...;
ZipFilesToResponse(HttpContext.Response, files, "download.zip");
}
}
方法更适用于常规MVC,而不是Web API。一种选择是简单地将此操作移动到MVC控制器而不是Web API控制器。
ZipFilesToResponse
由于ZipFilesToResponse
方法直接写入HttpContext.Response对象,因此无需返回任何内容。
或者,如果您想坚持使用纯粹的Web API,我们可以修改HttpResponseMessage
方法来创建[Route("DownloadFiles")]
[HttpGet]
public HttpResponseMessage DownloadFiles()
{
var files = ...;
return ZipContentResult(files, "download.zip");
}
protected HttpResponseMessage ZipContentResult(IEnumerable<Asset> files, string zipFileName)
{
var pushStreamContent = new PushStreamContent((stream, content, context) =>
{
using (var zipOutputStream = new ZipOutputStream(stream))
{
zipOutputStream.SetLevel(0); // 0 - store only to 9 - means best compression
foreach (var file in files)
{
var entry = new ZipEntry(file.FilenameSlug())
{
DateTime = DateTime.Now,
Size = file.Filesize
};
zipOutputStream.PutNextEntry(entry);
storageService.ReadToStream(file, zipOutputStream);
stream.Flush();
}
zipOutputStream.Finish();
zipOutputStream.Close();
}
stream.Close();
}, "application/zip");
pushStreamContent.Headers.Add("Content-Disposition", "attachment; filename=" + zipFileName);
return new HttpResponseMessage(HttpStatusCode.OK) { Content = pushStreamContent };
}
,然后从您的操作中返回。
{{1}}