简体   繁体   中英

How to congifure Visual Studio 2017 android emulator to work on localhost

I am using Xamarin.forms to consume an api. For that I have added a web project in my solution and I am using api's in its controller to manipulate data.

Firstly I deployed it on the Windows emulator all worked fine.

But when U deployed the same on Android, I get various exceptions such as-

System.Net.WebException: Failed to connect to localhost/127.0.0.1:53865

or:

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

I have tried solution such giving it internet permission, using ip address my system and using 10.2.2.2 but i am unable to run the application.

Below is the code for login it is giving Jsonreader exception-

public async Task<string> LoginAsync(string username, string password)
{
        var keyValues = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("username",username),
            new KeyValuePair<string, string>("password",password),
            new KeyValuePair<string, string>("grant_type","password")
        };

        var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.0.0:53865/Token");
        request.Content = new FormUrlEncodedContent(keyValues);

        var client = new HttpClient();
        var response = await client.SendAsync(request);
        var jwt = await response.Content.ReadAsStringAsync();
        var jwtDynamic = new JObject();
        jwtDynamic = JsonConvert.DeserializeObject<dynamic>(jwt);

        //dynamic jwtDynamic = JsonConvert.DeserializeObject(jwt);

        var accessToken = jwtDynamic.Value<string>("access_token");
        var accessExpires = jwtDynamic.Value<DateTime>(".expires");
        Settings.AccessTokenExpiration = accessExpires;

        Debug.WriteLine(jwt);

        return accessToken;
}

This is the Login - it is throwing a System.Net.Web.Exception :

public async Task<bool> RegisterAsync(string email, string password, string confirmpassword)
{
        var client = new HttpClient();

        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("http://localhost:53865/api/Account/Register", content);
  1. Configure your API URL to run on 127.0.0.1 instead of a localhost:

 // .NET Core Web.Api example public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup() .UseUrls(“http://127.0.0.1:5001“) .Build(); 

  1. Configure your Xamarin.Forms API consumer to have a conditional URL base:

  string apiUrl = null; if (Device.RuntimePlatform == Device.Android) apiUrl = “http://10.0.2.2:5001/api“; else if (Device.RuntimePlatform == Device.iOS) apiUrl = “http://localhost:5001/api“; else throw new UnsupportedPlatformException(); 

The problem with Android emulator is that it maps 10.0.2.2 to 127.0.0.1, not to localhost. However, the iOS Simulator uses the host machine network.

That should be it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM