Xamarin Forms HttpClient GetAsync

本文关键字:GetAsync HttpClient Forms Xamarin | 更新日期: 2023-09-27 17:56:08

我有一个 ASP.NET WebApi托管在Azure中。它没有基于 HTTP 标头或 Azure API 身份验证,小提琴手会话证明 API 功能齐全,并按请求和预期吐出数据。

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

    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"));

结果类别链接保持空。

以前有人遇到过这种情况吗?

需要注意的几点:

  • 虽然我怀疑这里是否有任何问题,但我有一个 MainViewModel 类,如下所示:

    public class MainViewModel
    {
        private readonly INavigation navigation;
        private readonly IContentService contentService;
        public IEnumerable<CategoryItem> Categories { get; set; }
        public MainViewModel(IContentService contentservice, INavigation nav)
        {
            this.navigation = nav;
            this.contentService = contentservice;
            SetCategoriesAsync();
        }
        private async Task SetCategoriesAsync()
        {
            var response = await this.contentService.GetCategories();
            this.Categories = (from c in response
                    select new CategoryItem()
                    {
                        //code removed but you get the idea
                    }).AsEnumerable();
        }
    }
    
  • 我的 MainPage.xaml.cs 在构造函数中有以下行。我认为这里也没有任何问题。

    this.MainViewModel = new MainViewModel(contentService, navService);
    this.CategoriesList.ItemsSource = this.MainViewModel.Categories;
    
  • 根据此链接,我已经通过nuget按出现顺序添加了对以下库的引用:Microsoft.BCL,Microsoft.BCL.Build,Microsoft.Net.Http

  • 我还没有使用ModernHttpClient。我计划在我让 HttpClient 工作后这样做,因为我相信它可以提高性能。

任何这方面的帮助将不胜感激。

Xamarin Forms HttpClient GetAsync

我遇到了这个确切的问题,它是由死锁引起的, 你怎么称呼这个方法? 通常我会去:

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

或者,如果它位于视图模型中,则可以使用Task.Run();

避免使用 .结果和 UI 中的计时器甚至事件处理程序都可能导致像这样的死锁。

希望这有帮助。