WebApi下载中的ASYNC错误

时间:2014-08-18 21:31:12

标签: c# asynchronous asp.net-web-api2 webclient-download

我有以下代码,用于下载多个文件,创建一个zip文件,并将文件返回给用户:

//In a WebAPI GET Handler
public async Task<HttpResponseMessage> Get(string id)
{
    try
    {
        var urlList = CacheDictionary<String, List<String>>.Instance[id];
        var helper = new Helper();
        var zipFile = await helper.CreateZipFormUrls(urlList);

        var response = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new MemoryStream();
        zipFile.Save(stream);
        response.Content = new ByteArrayContent(stream.ToArray());

        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
        response.Content.Headers.ContentLength = stream.Length;
        response.Content.Headers.ContentDisposition.FileName = "download.zip";

        return response;
    }
    catch (Exception)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

//In a Helper Class
public async Task<ZipFile> CreateZipFromUrls(List<string> urlList)
{
    using (var zip = new ZipFile())
    {
        var files = await ReturnFileData(urlList);
        foreach (var file in files)
        {
            var e = zip.AddEntry(GetFileNameFromUrlString(file.Key), file.Value);
        }

        return zip;
    }
}

static Task<Dictionary<string, byte[]>> ReturnFileData(IEnumerable<string> urls)
{
    Dictionary<Uri, Task<byte[]>> dictionary;
    using (var client = new WebClient())
    {
        dictionary = urls.Select(url => new Uri(url)).ToDictionary(
            uri => uri, uri => client.DownloadDataTaskAsync(uri));
        await Task.WhenAll(dictionary.Values);
    }

    return dictionary.ToDictionary(pair => Path.GetFileName(pair.Key.ToString()),
         pair => pair.Value.Result);
}

private string GetFileNameFromUrlString(string url)
{
    var uri = new Uri(url);
    return System.IO.Path.GetFileName(uri.LocalPath);
}

我总是得到:

异步操作仍未完成时异步模块或处理程序已完成

调用下载方法后无法访问任何断点。我究竟做错了什么?我在哪里看?

1 个答案:

答案 0 :(得分:1)

尝试等待此

dictionary = urls.Select(url => new Uri(url)).ToDictionary(
            uri => uri, uri => client.DownloadDataTaskAsync(uri));

问题可能是那个

client.DownloadDataTaskAsync(uri)); 

可能在代码的其余部分完成后仍在运行。