[英]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);
// .NET Core Web.Api example public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup() .UseUrls(“http://127.0.0.1:5001“) .Build();
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.