Xamarin 表单 HttpClient GetAsync

Xamarin Forms HttpClient GetAsync

我在 Azure 中托管了一个 ASP.NET WebApi。没有基于 HTTP Header 或 Azure API 的身份验证,fiddler 会话证明 API 功能齐全,并按要求和预期输出数据。

在我的 Xamarin 表单(PCL、iOS 和 Android)PCL 项目中,我在服务 class 中有以下代码:

    public async Task<IEnumerable<Link>> GetCategories()
    {
        IEnumerable<Link> categoryLinks = null;
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Using https to satisfy iOS ATS requirements
            var response = await client.GetAsync(new Uri("https://myproject.azurewebsites.net/api/contents"));

            //response.EnsureSuccessStatusCode(); //I was playing around with this to see if it makes any difference
            if (response.IsSuccessStatusCode)
            {
                var content = response.Content.ReadAsStringAsync().Result;
                categoryLinks = JsonConvert.DeserializeObject<IEnumerable<Link>>(content);
            }
        }
        return categoryLinks;
    }

我已经调试了代码,发现控件没有过去:

var response = await client.GetAsync(new Uri("https://myproject.azurewebsites.net/api/contents"));

因此 categoryLinks 仍然为空。

有人遇到过这个吗?

注意几点:

如有任何帮助,我们将不胜感激。

我确实遇到过这个问题,它是由死锁引起的,你是如何调用这个方法的?我通常去:

Device.BeginInvokeInMainThread(async () => 
{
   var categoriesList = await GetCategories();
});

或者如果它在您的视图模型中,您可以使用 Task.Run();

避免在您的 UI 中使用 .Result 和计时器,甚至事件处理程序也可能导致像这样的死锁。

希望这对您有所帮助。