下载WebApi时出现ASYNC错误
本文关键字:ASYNC 错误 WebApi 下载 | 更新日期: 2023-09-27 18:18:38
我有以下代码,用于下载多个文件,创建一个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);
}
我总是得到:
异步模块或处理程序在异步操作尚未完成时完成
并且在调用下载方法后无法到达任何断点。我做错了什么?我该往哪里看?
Try await on this
dictionary = urls.Select(url => new Uri(url)).ToDictionary(
uri => uri, uri => client.DownloadDataTaskAsync(uri));
问题可能是
client.DownloadDataTaskAsync(uri));
当你的代码完成后,可能还在运行。