![](/img/trans.png)
[英]How to pass error message to client from Web API controller's HttpPost async method returning Task<Type>?
[英]Returning Void in Async method from WEB API Controller
我從這個博客獲得的ASP.NET MVC 4 WEB API Controller中有這個異步方法: http : //www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload -with-ASP凈的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;
}
我的問題是為什么這個方法確實有一個返回類型的任務? 它還不清楚“在哪里”或“向誰”返回此任務? 這就像沒有人等待/接收返回的對象。
我想知道如果我像這樣返回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運行時等待它。 您可能會發現此視頻很有用。
async
大多數示例都假設UI上下文。 ASP.NET 還提供了一個上下文 ,但它是一個“請求”上下文 - 每個HTTP請求一個上下文。 我的async
/ await
post概述了這個“上下文”, async
/ await
FAQ更詳細。
如果返回類型為void,則不要等待對象返回..等待操作完成。 等待任務完成。
如果返回void,則無論異步操作的完成狀態如何,您都將立即返回204“無內容”響應消息。 這是在VoidResultConverter
的幫助下VoidResultConverter
。
注意:在RC上,您將看到它返回200“OK”響應,但是對於RTM,它將返回204“無內容”響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.