Xamarin App doesn't communicate with WebApi

I created Microsoft MVC WebApi for managining users accounts - login, register account ......

I have this WebApi on Computer in my local network on

When I open this "site" on my Android Phone - Google Chrome (, I show that this WebApi is working.

Now, I am trying to attempt this WebApi from Xamarin.Forms (deployed on Android). When I Click on the submit button (it should send the request to the server) it seems that nothing happened (after some time the app is frozen). Also when I am trying to debug this code it also seems that nothing happened :(

there is my method: (apiBaseUri =

    private async  Task<string> GetAPIToken(string userName, string password, string apiBaseUri) {

    JObject jObject = null;
        using (var client = new HttpClient())

            client.BaseAddress = new Uri(apiBaseUri);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            var formContent = new FormUrlEncodedContent(new[] {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", userName),
            new KeyValuePair<string, string>("password", password)

            HttpResponseMessage responseMessage = await client.PostAsync("/Token", formContent);

            var responseJson = await responseMessage.Content.ReadAsStringAsync();
            jObject = JObject.Parse(responseJson);


   catch (Exception ex)


    return jObject.GetValue("access_token").ToString();


The catch block doesn't catch any error ...

Any idea? thanks


  • AlinMaiorAlinMaior USMember ✭✭

    The code it's fine, it gets you the access token, which afterwards has to be added to the header of the api request. You must provide a valid username and password combination when calling it.
    Here's a full example:

  • LebowLebow CZMember

    But my problem asi, that my screen on my phone is frozen after clicked the button :(

    there is my code handler:

    loginButton.Clicked += OnLoginButtonClicked;

    And the method:
    async void OnLoginButtonClicked(object sender, EventArgs e ) {

            try {
               var token = GetAPIToken(usernameEntry.Text, passwordEntry.Text, "").Result;
            catch (Exception ex)
                App.IsUserLoggedIn = true;
                Navigation.InsertPageBefore(new MainPage(), this);
                 await Navigation.PopAsync();
  • LebowLebow CZMember

    solved, the problem was there:
    var token = await GetAPIToken(usernameEntry.Text, passwordEntry.Text, "");

Sign In or Register to comment.