c# - Xamarin 表单 HttpClient GetAsync

标签 c# azure asp.net-web-api xamarin.forms httpclient

我有一个托管在 Azure 中的 ASP.NET WebApi。它没有基于 HTTP header 或 Azure API 身份验证,并且 fiddler session 证明该 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"));

因此,categoryLinks 保持为空。

有人遇到过这种情况吗?

需要注意的几点:

  • 虽然我怀疑这里是否有任何问题,但我有一个如下所示的 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;
    
  • 根据 this link ,我已经通过 nuget 添加了对以下库的引用(按出现顺序排列):Microsoft.BCL、Microsoft.BCL.Build、M​​icrosoft.Net.Http

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

对此的任何帮助将不胜感激。

最佳答案

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

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

或者,如果它位于 View 模型内部,则可以使用 Task.Run();

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

希望这有帮助。

关于c# - Xamarin 表单 HttpClient GetAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38291977/

相关文章:

c# - EF LINQ 查询 if 子句中抛出空引用异常

c# - 如何从 ASP.NET Core Web API web-app 返回 Excel 文件?

javascript - MVC 枚举列表使用 Angular JS 在下拉列表中绑定(bind)

c# - 如何在根类中创建一些由所有派生类共享的字典?

azure - 流分析条件检查

python - Azure计时器触发函数 ".past_due"返回false

asp.net-web-api - Dynamics CRM Web API - 分配记录/更新所有者字段

c# - 使用 C# 以编程方式控制开源 GUI

c# - .Net 并行、任务 API 与常规线程

azure - 自动过期孤立订阅 (Azure ServiceBus Messaging SubscriptionClient)