Xamarin Forms,HttpClient类-GetStringAsync和GetAsync返回null值并快速退出功能 [英] Xamarin Forms, HttpClient class - GetStringAsync and GetAsync return null value and exit from function quickly

查看:182
本文介绍了Xamarin Forms,HttpClient类-GetStringAsync和GetAsync返回null值并快速退出功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行代码时,在调用GetStringAsync或GetAsync的函数中,这2次调用返回空值,并立即退出函数(所有未到达的代码)

when I run my code, in my function that call GetStringAsync or GetAsync, this 2 calls returns null value and immediately exit from my function (all code after is unreached )

我制作了一个可以从Web浏览器访问的Web api (在浏览器上访问的网址),也可以在模拟器浏览器中( Android模拟器上的浏览器),然后我尝试制作一个可以与其通信的xamarin表单

I make a web api that is is reachable from web browser (url reached on browser) , also in the emulator browser ( Browser on the Android Emulator ) then i try to make a xamarin forms that manages to communicate with it

class MainPageViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;



    public MainPageViewModel()
    {
        GetEmployees();
    }



    private async void GetEmployees()
    {
        using (var httpClient = new HttpClient())
        {
            var uri = "http://192.168.1.135:8092/api/Masters/GetEmployees/";

            var result = await httpClient.GetStringAsync(uri);


            var EmployeeList = JsonConvert.DeserializeObject<List<Employee>>(result);

            Employees = new ObservableCollection<Employee>(EmployeeList);
        }

    }

    ObservableCollection<Employee> _employees;

    public ObservableCollection<Employee> Employees
    {

        get
        {
            return _employees;
        }

        set
        {
            _employees = value;
            OnPropertyChanged(nameof(Employee));

        }

    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

class MainPageViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private const string ApiBaseAddress = "http://192.168.1.135:8092/api/Masters/GetEmployees/";

    public MainPageViewModel()
    {
        GetEmployees();
    }

    private HttpClient CreateClient()
    {
        var httpClient = new HttpClient
        {
            BaseAddress = new Uri(ApiBaseAddress)
        };

        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        return httpClient;
    }

    private async void GetEmployees()
    {

        using (var httpClient = CreateClient())
        {
            var response = await httpClient.GetAsync(ApiBaseAddress).ConfigureAwait(false);

            var test = response;

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                if (!string.IsNullOrWhiteSpace(json))
                {
                    var EmployeeList = JsonConvert.DeserializeObject<List<Employee>>(json);

                    Employees = new ObservableCollection<Employee>(EmployeeList);

                }

            }

            response.Dispose();
        }
    }

    ObservableCollection<Employee> _employees;

    public ObservableCollection<Employee> Employees
    {

        get
        {
            return _employees;
        }

        set
        {
            _employees = value;
            OnPropertyChanged(nameof(Employee));

        }

    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

我希望var result = await httpClient.GetStringAsync(uri);

 var response = await httpClient.GetAsync(ApiBaseAddress).ConfigureAwait(false);

返回某些内容,但实际输出为null,并且未到达此后的代码,因为此2调用立即从函数中退出

returns something but the actual output is null and the code after is unreached because this 2 calls exit immediatly from the function

推荐答案

避免混合使用异步/等待和阻塞.Wait()或.Result

Avoid mixing async/await and blocking calls like .Wait() or .Result

重构代码,使其始终保持异步状态.

Refactor your code to be async all the way through.

public MainPageViewModel()
{
   var EmployeeList =  GetEmployees();
   Employees = new ObservableCollection<Employee>(EmployeeList.Result);
}



private async Task<List<Employee>> GetEmployees()
{
   using (var httpClient = CreateClient())
   {
     var response = await httpClient.GetAsync(ApiBaseAddress).ConfigureAwait(false);

     var test = response;

     if (response.IsSuccessStatusCode)
     {
       var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

       if (!string.IsNullOrWhiteSpace(json))
       {
          var EmployeeList = JsonConvert.DeserializeObject<List<Employee>>(json);

          return EmployeeList;

       }                    

     }

     return null;
    }

}

这篇关于Xamarin Forms,HttpClient类-GetStringAsync和GetAsync返回null值并快速退出功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆