使用 VS 2010、VB.NET、HTTPClient、.NET 4.0 和 Windows 窗体。
我正在尝试让 Windows 应用程序使用来 self 创建的 Web API 的 JSON。 Web API 运行良好,我可以从浏览器查看结果。发现这篇文章我一直试图仅使用 VB.NET 而不是 C# 来工作。 http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-wpf-application
代码的关键部分是这个函数:
private void GetProducts(object sender, RoutedEventArgs e)
{
btnGetProducts.IsEnabled = false;
client.GetAsync("api/products/2").ContinueWith((t) =>
{
if (t.IsFaulted)
{
MessageBox.Show(t.Exception.Message);
btnGetProducts.IsEnabled = true;
}
else
{
var response = t.Result;
if (response.IsSuccessStatusCode)
{
response.Content.ReadAsAsync<IEnumerable<Product>>().
ContinueWith(t2 =>
{
if (t2.IsFaulted)
{
MessageBox.Show(t2.Exception.Message);
btnGetProducts.IsEnabled = true;
}
else
{
var products = t2.Result;
_products.CopyFrom(products);
btnGetProducts.IsEnabled = true;
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
我尝试将其转换为 VB.NET,但我遇到了 t.Result 问题,提示“'Result' 不是 'System.Threading.Tasks.Task' 的成员。”
这是我将其转换为 VB.NET 的尝试:
Private Sub GetProducts(sender As Object, e As RoutedEventArgs)
btnGetProducts.IsEnabled = False
client.GetAsync("api/products/2") _
.ContinueWith(Of HttpResponseMessage) _
(Function(t)
If t.IsFaulted Then
MessageBox.Show(t.Exception.Message)
btnGetProducts.IsEnabled = True
Else
'***************************************************************
Dim response = t.Result 'This is the line that is giving me grief. Error Msg: 'Result' is not a member of 'System.Threading.Tasks.Task'.
'***************************************************************
If response.IsSuccessStatusCode Then
response.Content.ReadAsAsync(Of IEnumerable(Of SendNotice)).ContinueWith _
(Function(t2)
If t2.IsFaulted Then
MessageBox.Show(t2.Exception.Message)
btnGetProducts.IsEnabled = True
Else
Dim products = t2.Result
_lstSN.CopyFrom(products)
btnGetProducts.IsEnabled = True
End If
End Function, TaskScheduler.FromCurrentSynchronizationContext())
End If
End If
End Function, TaskScheduler.FromCurrentSynchronizationContext())
End Sub
知道为什么我会收到此错误以及我的代码中缺少什么以允许我捕获返回的 JSON 数据吗?
谢谢!
最佳答案
这是因为 VB.NET 类型推断在 Visual Studio 2010 中不太好。您需要通过指定 返回的实际类型来为编译器提供一些额外的帮助client.GetAsync()
,如下所示:
client _
.GetAsync("api/products/2") _
.ContinueWith( _
Sub(t As Task(Of HttpResponseMessage))
...
End Sub, _
TaskScheduler.FromCurrentSynchronizationContext())
注意:我已将您的 Function 更改为 Sub,因为我没有看到任何 Return 语句。
关于c# - 转换 - 'Result' 不是 'System.Threading.Tasks.Task' 的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21126519/