【发布时间】:2014-01-14 23:54:16
【问题描述】:
使用 VS 2010、VB.NET、HTTPClient、.NET 4.0 和 Windows 窗体。
我正在尝试让 Windows 应用程序使用来自我创建的 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 而不是 C#。
-
看起来它认为它的
Task不是Task<T>
标签: c# vb.net asp.net-web-api dotnet-httpclient vb.net-to-c#