问题描述
我对我们的WebAPI后端有一个非常简单的REST查询(由许多应用程序使用),并且在Android和Windows下运行良好,但是在iOS中,它失败,并显示对象引用未设置为对象实例"错误.在下面的代码中,moHttpClient和loUri均被实例化.我试过将对GetEmployeeRecord的调用包装在Device.BeginInvokeOnMainThread中,但这无济于事.我已经在Visual Studio和Mac上升级到Xamarin的最新稳定版本.为什么它可以在其他操作系统上运行但不能在iOS上运行?
I have a very simple REST query to our WebAPI back end (used by a number of applications) and it works fine under Android and Windows but in iOS it fails with an "Object reference not set to an instance of an object" error. In the code below, both moHttpClient and loUri are instantiated. I've tried wrapping the call to GetEmployeeRecord in Device.BeginInvokeOnMainThread but that doesn't help either. I have upgraded to the latest stable version of Xamarin in Visual Studio and on my Mac. Why is it working in the other OSs but not iOS?
private async void btnTest_Clicked(object sender, EventArgs e)
{
await GetEmployeeRecord();
}
private async Task GetEmployeeRecord()
{
try
{
var loUri = new Uri("https://my.website.com/mobile.webapp/api/employees?key=6c6f2c06-a444-4e54-bd77-b5f594c29910");
var loResponse = await moHttpClient.GetAsync(loUri);
if (loResponse.IsSuccessStatusCode)
{
var lcJson = await loResponse.Content.ReadAsStringAsync();
await DisplayAlert("Employee", lcJson, "OK");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
DisplayAlert("Get Employee Record", ex.Message, "OK");
});
}
}
使用GetAsync行上的断点,可以同时实例化moHttpClient和loUri.但是,将鼠标悬停在GetAsync上会显示一条消息,指出GetAsync是未知成员.怎么可能?
Using a breakpoint at the GetAsync line, both moHttpClient and loUri are instantiated. However, mousing over GetAsync gives a message that GetAsync is an unknown member. How can that be?
我刚刚检查了一下,似乎这个Unknown成员也出现在Android中.但是,使用Android,它实际上可以执行.
I just checked and it seems this Unknown member occurs with Android too. But with Android it actually executes.
推荐答案
为了使http查询适用于iOS,我必须在PCL项目中安装NuGet包Microsoft.Net.Http,这是代码所在正在运行.
In order to get the http query to work for iOS I had to install the NuGet package Microsoft.Net.Http in the PCL project, which is where the code is running.
这篇关于Xamarin表单HttpClient GetAsync仅在iOS中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!