1

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 )

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));
    }
}

or

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));
    }
}

I expect that var result = await httpClient.GetStringAsync(uri);

or

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

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

6
  • Have you tried to access to that url with your browser? Commented Aug 12, 2019 at 7:08
  • yes, I already said that with the browser it works, only with calls, unfortunately, does not work Commented Aug 12, 2019 at 7:37
  • Maybe your running emulator (Android or iOS) don't have access to that url, can you start your emulator, use the installed browser and try to enter into that url? Commented Aug 12, 2019 at 7:53
  • Try the URL in the device browser. Commented Aug 12, 2019 at 7:59
  • using (var httpClient = CreateClient()) is wrong, HttpClient is intended to be instantiated once per application, rather than per-use. learn.microsoft.com/en-us/dotnet/api/… Commented Aug 12, 2019 at 8:04

1 Answer 1

1

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;
    }

}
Sign up to request clarification or add additional context in comments.

5 Comments

Throws Exception: Cleartext HTTP traffic to 192.168.1.135 not permitted
I've already read it but for me is not working. I belive my problem is the ssl certificate because if i try to connecting to web api with https, I can't
Did you try to change another url?
Ok, problem solved adding these lines of code into AndroidManifest.xml <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system" /> </trust-anchors> </base-config>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.