繁体   English   中英

如何配置Visual Studio 2017 Android模拟器在本地主机上工作

[英]How to congifure Visual Studio 2017 android emulator to work on localhost

我正在使用Xamarin.forms来使用api。 为此,我在解决方案中添加了一个Web项目,并在其控制器中使用api来处理数据。

首先,我将其部署在Windows模拟器上一切正常。

但是当U在Android上部署相同的软件时,我会遇到各种异常,例如-

System.Net.WebException:无法连接到localhost / 127.0.0.1:53865

要么:

Newtonsoft.Json.JsonReaderException:解析值时遇到意外字符:<。 路径'',第0行,位置0。

我尝试过这样的解决方案,例如授予其Internet权限,使用我的系统的ip地址并使用10.2.2.2,但是我无法运行该应用程序。

以下是登录代码,它为Jsonreader提供了例外-

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;
}

这是登录名-它抛出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. 将您的API URL配置为在127.0.0.1而不是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. 配置您的Xamarin.Forms API使用者以使用条件URL:

  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(); 

Android模拟器的问题在于它将10.0.2.2映射到127.0.0.1,而不是localhost。 但是,iOS Simulator使用主机网络。

就是这样!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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