Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin: Connect to locally hosted web service

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.

like image 574
jayeshmon kj Avatar asked Jun 30 '15 07:06

jayeshmon kj


People also ask

Is Xamarin deprecated?

Xamarin. Forms will continue to receive service releases through November 2022. Attachments: Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total. Attachments: Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Is Xamarin native or cross platform?

Xamarin apps are native apps! Whether you're designing a uniform UI across platforms or building a native user interface, your apps will behave the way users expect.


1 Answers

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.

like image 155
Culy Ch Avatar answered Sep 26 '22 00:09

Culy Ch