Gustavo Oka
Gustavo Oka

Reputation: 79

Task was cancelled when trying to download file from WebApi

I got the error "Task was cancelled" when I'm trying to download a zip file from Web API. What am I doing wrong ?

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Threading.Tasks.TaskCanceledException: A task was canceled.

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;
}

Upvotes: 3

Views: 1430

Answers (1)

Jose Cordero
Jose Cordero

Reputation: 526

I was getting this error while trying to download an Excel file calling my API. I didn't had ATP implemented on this method so it was confusing at first. This was my initial code:

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);
}

After thinking and making some changes this came up:

...

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);

...

As you can see I was enclosing the stream inside an using statement. This was causing that the request wasn't being completed since the content was not available for the response.

Upvotes: 1

Related Questions