gpt4 book ai didi

c# - 从 WEB API Controller 返回异步方法中的 Void

转载 作者:太空狗 更新时间:2023-10-29 18:36:06 24 4
gpt4 key购买 nike

我从这个博客获得的 ASP.NET MVC 4 WEB API Controller 中有这个异步方法: http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/

  public async Task<IList<RecivedFile>> Post()
{
List<RecivedFile> result = new List<RecivedFile>();
if (Request.Content.IsMimeMultipartContent())
{
try
{
MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/USER-UPLOADS"));

IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream);
IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames;
IList<string> newFiles = new List<string>();

foreach (var item in bodyPartFiles)
{
var newName = string.Empty;
var file = new FileInfo(item.Value);

if (item.Key.Contains("\""))
newName = Path.Combine(file.Directory.ToString(), item.Key.Substring(1, item.Key.Length - 2));
else
newName = Path.Combine(file.Directory.ToString(), item.Key);

File.Move(file.FullName, newName);
newFiles.Add(newName);
}

var uploadedFiles = newFiles.Select(i =>
{
var fi = new FileInfo(i);
return new RecivedFile(fi.Name, fi.FullName, fi.Length);
}).ToList();

result.AddRange(uploadedFiles);
}
catch (Exception e)
{
}
}
return result;
}

我的问题是,为什么这个方法的返回类型是 Task?不清楚它返回此任务的“到哪里”或“给谁”?就像没有人在等待/接收返回的对象。

我想知道如果我这样返回 void 会产生什么影响:

编辑:

我试过下面的代码,它完全破坏了程序。就像运行时丢失了对代码的引用,代码本身没有完成运行。

    public async void Post()
{
List<RecivedFile> result = new List<RecivedFile>();
if (Request.Content.IsMimeMultipartContent())
{
try
{
MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/USER-UPLOADS"));

IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream);
IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames;
IList<string> newFiles = new List<string>();

foreach (var item in bodyPartFiles)
{
var newName = string.Empty;
var file = new FileInfo(item.Value);

if (item.Key.Contains("\""))
newName = Path.Combine(file.Directory.ToString(), item.Key.Substring(1, item.Key.Length - 2));
else
newName = Path.Combine(file.Directory.ToString(), item.Key);

File.Move(file.FullName, newName);
newFiles.Add(newName);
}

}
catch (Exception e)
{
}
}

}

最佳答案

ASP.NET 运行时等待它。你可能会发现 this video有用。

async 的大多数示例都假定一个 UI 上下文。 ASP.NET also provides a context ,但它是一个“请求”上下文——每个 HTTP 请求一个。我的async/await post给出了这个“上下文”的概述,以及 async/await FAQ进入更多细节。

关于c# - 从 WEB API Controller 返回异步方法中的 Void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11915138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com