Http获取请求未获取任何数据

时间:2019-03-24 17:45:23

标签: c# http asp.net-web-api https xamarin.forms

我将我的Web Api在线安装在生产服务器上,到目前为止,在邮递员和Xamarin表单中都可以正常运行,直到我需要执行“获取请求”并且不返回任何数据为止。实际上,它停止在GetAsStringAsync行,并且不会继续。相反,它跳出了方法,然后仅此而已。

有人知道这个问题可能是什么吗?我已经检查并确保我的Internet和Uri也都在工作。

这是我在Xamarin表单中进行获取的地方:

public async Task<List<OfferModel>> AllOffers()
{
    var httpclient = new HttpClient();
    httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
    //it does not continue after this line, it jumps out of the method instead
    var response = await httpclient.GetStringAsync(UrlConstants.offerurl);
    var data =JsonConvert.DeserializeObject<List<OfferModel(response);
    return data;
}

1 个答案:

答案 0 :(得分:1)

  

解决方案1 ​​

您能否通过等待者尝试访问任务,它可能要等到结果响应后才可以

    public class HttpHelperService
    {
                public async Task<List<OfferModel>> AllOffers()
                {
                    List<OfferModel> result;
                    string responseBody;
                    using (HttpClient client = new HttpClient())
                    {
                        try
                        {
                            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
                            HttpResponseMessage response = client.GetStringAsync(new Uri(UrlConstants.offerurl)).GetAwaiter().GetResult();
                            result = JsonConvert.DeserializeObject<List<OfferModel>>(response);
                        }
                        catch (Exception ex)
                        {
                            result = null;
                        }
                        return result;
                    }
                }
        }
  

解决方案2

public class MyPage : ContentPage
{
//Here is your page constructor
    public MyPage()
    {
       GetServices(); //--> call here without awaiter
    }
}

//Here is your awaiter method
    private async void GetServices()
    {
       LoadingPopupService.Show();
       var result = await HttpService.AllOffers();
        LoadingPopupService.Hide();
    }

//Here is your service.
    public async Task<List<OfferModel>> AllOffers()
    {
        var httpclient = new HttpClient();
        httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
        var response = await httpclient.GetStringAsync(UrlConstants.offerurl);
        var data =JsonConvert.DeserializeObject<List<OfferModel(response);
        return data;
    }