locked
"System.Net.WebException: 'Failed to connect to localhost/127.0.0.1:44391'" I got those error, RRS feed

  • Question

  • User391032 posted

    Hi I am new for Xamarin. form,

    I try to use Asp.net Api, and integrate with my Xamarin form app, but cannot connect to my Xamarin App with Api.

    but using Postman, directly input data to my Asp.net Api working perfectly.

    I got this message from Xamarin form. "System.Net.WebException: 'Failed to connect to localhost/127.0.0.1:44391'"

    My code below:

    public class ApiServices
    {
        public async Task<bool> RegisterAsync(string phone, string password, string confirmPassword)
        {
            var client = new HttpClient();
    
            var model = new RegisterBindingModel
            {
                phone = phone,
                password = password,
                passwordconfirm = confirmPassword
            };
            var json = JsonConvert.SerializeObject(model);
    
            HttpContent content = new StringContent(json);
    
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 
    
            var response = await client.PostAsync("http://localhost:44391/api/login/", content);
    
            return response.IsSuccessStatusCode;
        }
    }
    

    That is my code for connecting Api.

    I don't know why i got 127.0.0.1 coming from.

    Thank you. guys.

    Tuesday, December 24, 2019 12:40 AM

Answers

  • User369979 posted

    localhost is used to point out your local machine's IP address. If you tested on the machine which runs your server service with postman it could easily recognize this. You haven't mentioned which environment you are testing with(Emulators or real device) I guess you are testing it on an Android emulator. Then we can't use localhost as the local machine's IP address as emulator runs in a virtual machine. They have their own local IP address. Try to replace it with your server machine's IP address you could find it through the ipconfig command instruction using cmd: Here is my local IP address and the request uri should be:

    "http://172.17.13.28:44391/api/login/"
    
    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Tuesday, December 24, 2019 2:56 AM