How to Access using Xamarin.Forms local Web API with Emulator for Visual Studio?

3.2k Views Asked by At

I've created .NET Framework API which contains authentication, I launch the Web API using Jetbrains Rider and I run my Xamarin.Forms application using Visual Studio and I can't access any data from my Web API nor post any.

The Webservice class:

private readonly HttpClient _client;

public AccountService()
{
    _client = new HttpClient
    {
        MaxResponseContentBufferSize = 256000
    };
}

public async Task RegisterAsync(string email, string password, string confirmPassword)
{
    var url = "http://169.254.80.80:61348/api/Account/Register";
    var model = new RegisterBindingModel()
    {
        Email = email,
        Password = password,
        ConfirmPassword = confirmPassword
    };

    var json = JsonConvert.SerializeObject(model);

    HttpContent content = new StringContent(json);

    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    var response = await _client.PostAsync(url, content);
}

The initiation of the registration

private async void Register()
{
    try
    {
        using (UserDialogs.Instance.Loading())
        {
            await _accountServices.RegisterAsync
                (Email, Password, ConfirmPassword);
        }
        UserDialogs.Instance.Alert("Register Successful");

        await _navigation.PushAsync(new LoginPage());
    }
    catch
    {
        UserDialogs.Instance.Alert("Something wrong happened, Try again");
    }
}

I've tried to access the localhost through Emulator using these IPs:

  • 10.0.3.2
  • 10.0.2.2
  • 169.254.80.80

And I've tried my default gateways and my local IP address with and without ports, in regardless using postman i can work with my api flawlessly.

I don't get errors but the connection status code is not successful and I don't get any data and the newly registered account won't be posted to the api.

EDIT: As for the answers I've changed my method to this:

        public async Task<string> RegisterAsync(string email, string password, string confirmPassword)
    {
        var client = new HttpClient()
        {
            BaseAddress = new Uri("http://169.254.80.80:61348/")
        };
        var postData = new List<KeyValuePair<string, string>>();
        var nvc = new List<KeyValuePair<string, string>>();
        nvc.Add(new KeyValuePair<string, string>("email", email));
        nvc.Add(new KeyValuePair<string, string>("password", password));
        nvc.Add(new KeyValuePair<string, string>("confirmPassword", confirmPassword));
        var req = new HttpRequestMessage(HttpMethod.Post, "api/Account/Register") { Content = new FormUrlEncodedContent(nvc) };
        var res = await client.SendAsync(req);
        if (res.IsSuccessStatusCode)
        {
            string result = await res.Content.ReadAsStringAsync();
            string test = JsonConvert.DeserializeObject<string>(result);
            return test;
        }

        return null;
    }

and i call the web api using postman like this: http://localhost:61348/api/Account/Register

1

There are 1 best solutions below

6
Ronak Shetiya On

I always prefer Newtonsoft Json.NET to carry out web request here is the code I have implemented in my case and it works great for me.

public static async Task<string> ResgisterUser(string email, string password, string confirmPassword)
{
    var client = new HttpClient(new NativeMessageHandler());
    client.BaseAddress = new Uri("http://192.168.101.119:8475/");
    var postData = new List<KeyValuePair<string, string>>();
    var nvc = new List<KeyValuePair<string, string>>();
    nvc.Add(new KeyValuePair<string, string>("email", email));
    nvc.Add(new KeyValuePair<string, string>("password", password));
    nvc.Add(new KeyValuePair<string, string>("confirmPassword",confirmPassword));
    var req = new HttpRequestMessage(HttpMethod.Post, "api/Vendor/Register") { Content = new FormUrlEncodedContent(nvc) };
    var res = await client.SendAsync(req);
    if (res.IsSuccessStatusCode)
    {
        string result = await res.Content.ReadAsStringAsync();
        string test= JsonConvert.DeserializeObject<string>(result);
        return test;
    }
}

Hope it works for you.