Xamarin Forms HttpClient GetAsync 仅在 iOS 中失败 [英] Xamarin Forms HttpClient GetAsync Fails in iOS Only

查看:23
本文介绍了Xamarin Forms HttpClient GetAsync 仅在 iOS 中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我们的 WebAPI 后端(由许多应用程序使用)有一个非常简单的 REST 查询,它在 Android 和 Windows 下运行良好,但在 iOS 中它失败并显示对象引用未设置为对象的实例"错误.在下面的代码中,moHttpClient 和 loUri 都被实例化.我试过在 Device.BeginInvokeOnMainThread 中包装对 GetEmployeeRecord 的调用,但这也无济于事.我已在 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?

我刚刚查了一下,这个未知成员似乎也出现在 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 Forms HttpClient GetAsync 仅在 iOS 中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆