我遇到了从正常异步 ApiController 返回“立即”响应的问题。代码如下,寻找感叹号。用例是内容类型检查失败,我想发回错误响应消息。第一个版本挂起 Visual Studion 2010(和 Fiddler)。第二个作品。
我的问题是,为什么我不能使用我最初的方法来返回仅传回响应对象的虚拟任务?
public class MyController : ApiController
{
public Task<HttpResponseMessage> Post([FromUri]string arg)
{
HttpResponseMessage response = null;
// synchronous validation
if (Request.Content.Headers.ContentType.MediaType != @"image/jpeg")
{
response = Request.CreateErrorResponse(
HttpStatusCode.UnsupportedMediaType,
"Invalid Content-Type.");
}
if (response == null) // no immediate response, switch to async
{
// work done here
}
else // immediate response, but we need to wrap in a task for caller to fetch
{
// !!!! this one doesn't work !!!
return new Task<HttpResponseMessage>( () => response);
// !!! this one does !!!
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
}
}
}