我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
这是登录名-它抛出了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);
Run Code Online (Sandbox Code Playgroud)
// .NET Core Web.Api example
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args)
.UseStartup()
.UseUrls(“http://127.0.0.1:5001“)
.Build();
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
Android模拟器的问题在于它将10.0.2.2映射到127.0.0.1,而不是localhost。但是,iOS Simulator使用主机网络。
就是这样!
归档时间: |
|
查看次数: |
2135 次 |
最近记录: |