Xamarin: Connect to locally hosted web service

jayeshmon kj picture jayeshmon kj · Jun 30, 2015 · Viewed 31.3k times · Source

I want to create a web api application to connect xamarin with android.
I had tried a lot, but some connection errors are coming.

My code is given below:

public async Task<JsonValue> find(int ID)
    {
     using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:49836");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage result = client.GetAsync("api/Product").Result;
           return JsonConvert.DeserializeObject<JsonValue>(await result.Content.ReadAsStringAsync());                
     }       
    }
    }

I 'm getting the error like the below

System.Net.WebException: Error: ConnectFailure (Connection refused) ---> System.Net.Sockets.SocketException: Connection refused

Can any one help. Any help is appreciated.

Answer

Culy Ch picture Culy Ch · Mar 18, 2018

If you're using an Android Emulator then asking for the localhost web service won't work, because you're looking at the localhost of the emulator. How can you fix this? Well, Android Emulator has a magic address http://10.0.2.2:your_port that points to 127.0.0.1:your_port on your host machine.Take a look here. Because it points to an IP and not localhost, you need to go into your project solution, in .vs folder->config->applicationhost.config and change this <binding protocol="http" bindingInformation="*:13142:localhost" /> into <binding protocol="http" bindingInformation="*:13142:127.0.0.1" />, where 13142 is my port, yours may be different. Restart IIS Express and you're good to go.