1
votes

I want to call web api(which is on my local visual studio) through Xamarin forms but its not calling my web api. I am using visual studio android emulator.

I am using visual studio 2015 update 3 and here is my code

 public class DataService
{

    HttpClient client = new HttpClient();
    string apiPaht = "http://10.0.2.2:19367/api/";
    //string apiPaht = "http://localhost:19367/api/";

    public async Task<List<CustomerApp>> GetTodoItemsAsync()
    {
        var response = await client.GetStringAsync(apiPaht+ "APICustAccount/getTestData");
        var todoItems = JsonConvert.DeserializeObject<List<CustomerApp>>(response);
        return todoItems;
    }

}

Code on my xamal.cs

  async void RefreshData()
    {
        List<CustomerApp> listCust = await _dService.GetTodoItemsAsync();           
        todoList.ItemsSource = listCust;
        string aa = "";
    }

   protected void btn_click(object sender, EventArgs e)
    { 
      RefreshData();
    }
1
Does your application have internet permission? i. e. <uses-permission android:name="android.permission.INTERNET" /> in the AndroidManifest.xmlTamás Szabó
Can you reach that URL from the emulator browser?Gerald Versluis
yes i have internet permission @tamas Szabosatyender
And can you access the API through browser (either from the emulator or from your PC)?Tamás Szabó
i am new in mobile development i don't know using emulator browser. please tell me using emulator browsersatyender

1 Answers

0
votes

Hi Please try the below code and let me know if you have any query.

Get Method:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://10.0.2.2:19367/api/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("APICustAccount/getTestData").Result;
if (response.StatusCode == HttpStatusCode.OK)
{
    var result = await response.Content.ReadAsStringAsync();
    var todoItems = JsonConvert.DeserializeObject<List<CustomerApp>>(result);
}

I have tested the above code and it's working for me.