首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >[医] HttpClient GetAsync

[医] HttpClient GetAsync
EN

Stack Overflow用户
提问于 2016-07-10 12:40:40
回答 1查看 4.9K关注 0票数 1

我在Azure有一个ASP.NET WebApi。它上没有基于HTTP报头或Azure API的身份验证,而fiddler会话证明该API是完全功能的,并按请求和预期输出数据。

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

代码语言:javascript
复制
    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;
    }

我已经调试了代码,并注意到控件没有经过:

代码语言:javascript
复制
var response = await client.GetAsync(new Uri("https://myproject.azurewebsites.net/api/contents"));

因此,categoryLinks仍然是空的。

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

有几件事要注意:

  • 虽然我怀疑这里是否有任何问题,但我有一个MainViewModel类,如下所示: 公共类MainViewModel {私有只读INavigation导航;私有只读IContentService contentService;公共IEnumerable类别{ get;set;}公共MainViewModel(IContentService内容服务,INavigation nav) { this.navigation = nav;this.contentService =内容服务;SetCategoriesAsync();}私有异步任务SetCategoriesAsync() { var响应=等待this.contentService.GetCategories();this.Categories =(响应时从c中选择新的CategoryItem() {//代码已删除,但您得到了idea }).AsEnumerable();}
  • 我的MainPage.xaml.cs在构造函数中有以下行。我也不认为这里有任何问题。 this.MainViewModel =新MainViewModel(contentService,navService);this.CategoriesList.ItemsSource = this.MainViewModel.Categories;
  • 根据this link,我已经按照外观顺序通过nuget添加了对以下库的引用: Microsoft.BCL、Microsoft.BCL.Build、Microsoft.Net.Http
  • 到目前为止我还没有使用ModernHttpClient。我计划这样做,一旦我让HttpClient工作,因为我相信它会提高性能。

如能在这方面提供任何协助,将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-11 05:38:26

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

代码语言:javascript
复制
Device.BeginInvokeInMainThread(async () => 
{
   var categoriesList = await GetCategories();
});

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

避免使用.Result,而UI中的计时器--甚至事件处理程序--也可能导致类似于此的死锁。

希望这能有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38291977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档