【发布时间】:2016-07-10 12:40:40
【问题描述】:
我有一个托管在 Azure 中的 ASP.NET WebApi。它没有基于 HTTP Header 或 Azure API 身份验证,fiddler 会话证明 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、Microsoft.Net.Http
李> 我还没有使用 ModernHttpClient。我计划在 HttpClient 工作后这样做,因为我相信它可以提高性能。
对此的任何帮助将不胜感激。
【问题讨论】:
-
启用来自msdn.microsoft.com/en-us/library/x85tt0dd.aspx 的所有异常,看看你是否在
GetAsync上得到一个。
标签: c# azure asp.net-web-api xamarin.forms httpclient