我收到错误" 任务已取消"当我试图从Web API下载zip文件时。我做错了什么?
描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.Threading.Tasks.TaskCanceledException:任务已取消。
using (var ms = new MemoryStream())
{
using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
foreach (var attachment in item)
{
var entry = zipArchive.CreateEntry(attachment.ItemAnalisado.Arquivo.Nome, CompressionLevel.Fastest);
using (var stream = entry.Open())
{
var dadosArquivo = File.ReadAllBytes(
Path.Combine(CaminhoImagens,
attachment.ItemAnalisado.Arquivo.ProcessoId.ToString(),
attachment.ItemAnalisado.Arquivo.SubPastaId.ToString(),
attachment.ItemAnalisado.Arquivo.Id.ToString()));
stream.Write(dadosArquivo, 0, dadosArquivo.Length);
//stream.Position = 0;
stream.Close();
}
}
}
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
ms.Position = 0;
response.Content = new StreamContent(ms);
ms.Dispose();
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "teste.zip";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;
}
答案 0 :(得分:0)
尝试下载调用我的API的Excel文件时遇到此错误。我没有在此方法上实施ATP,因此一开始令人感到困惑。这是我的初始代码:
public IHttpActionResult Get([FromUri] string id, [FromUri] SurveyReportRequestType requestType) {
byte[] excelData = System.Text.Encoding.UTF8.GetBytes("Boobs out!");
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
using (var stream = new MemoryStream(excelData))
{
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Data.xls"
};
}
return ResponseMessage(result);
}
考虑并做出一些更改后,出现了这种情况:
...
byte[] excelData = System.Text.Encoding.UTF8.GetBytes("Boobs aout!");
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(excelData);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Data.xls"
};
return ResponseMessage(result);
...
如您所见,我将 stream 括在 using 语句中。由于内容不可用于响应,这导致请求未完成。