这只是一个简单的异步任务,但我总是遇到奇怪的编译器错误。此代码来自ASP.NET 4项目中的Web API服务,使用VS2010创建。
Even ContinueWith(非泛型)隐式返回Task,但此错误仍然存在。
代码:
public class TestController : ApiController
{
public Task<HttpResponseMessage> Test()
{
string url = "http://www.stackoverflow.com";
var client = new HttpClient();
return client.GetAsync(url).ContinueWith<HttpResponseMessage>((request) =>
{
// Error 361 'System.Threading.Tasks.Task' does not contain a definition
// for 'Result' and no extension method 'Result' accepting a first argument
// of type 'System.Threading.Tasks.Task' could be found
// (are you missing a using directive or an assembly reference?)
var response = request.Result;
response.EnsureSuccessStatusCode();
// Error 364 Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>' to 'System.Net.Http.HttpResponseMessage'
return response.Content.ReadAsStringAsync().ContinueWith<HttpResponseMessage>((read) =>
{
return new HttpResponseMessage();
});
});
}
}
答案 0 :(得分:5)
364错误完全正常,因为您要返回Task<Task<HttpResponseMessage>>
而不是Task<HttpResponseMessage>
。一旦你修复了361错误也会消失。
所以你可以Unwrap
结果:
public Task<HttpResponseMessage> Test()
{
string url = "http://www.stackoverflow.com";
var client = new HttpClient();
return client.GetAsync(url).ContinueWith(request =>
{
var response = request.Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().ContinueWith(t =>
{
var result = new HttpResponseMessage();
response.CreateContent(t.Result);
return response;
});
}).Unwrap();
}