我正在通过本教程学习 Xamarin -。如果用邮递员发送请求,一切正常。但如果我想使用 android 模拟器,它就不起作用。而且我无法使用 UWP,因为必须启用开发人员模式,而且我在公司计算机上没有管理员权限。我在我的私人计算机上启用了开发人员模式,它可以在 UWP 上运行,但不能在 Android 模拟器上运行。在教程中使用的是UWP,那家伙说对于android模拟器需要一些配置,但他没有透露任何细节。
我读了很多文章,问题似乎出在我的后端(在本地主机上运行)和 android 模拟器之间的连接。 android 模拟器是一台单独的机器试图调用我的本地主机,这是否正确?我尝试将 localhost 更改为 127.0.0.1 或 10.0.2.2,并尝试了以下所有选项本文 https://developer.android.com/studio/run/emulator-networking。但它不起作用。
我说的对吗 localhost 必须改变?如果是的话,在哪里?还是其他地方有问题?
API服务注册方法:
public async Task<bool> RegisterAsync(string email, string password, string confirmPassword)
{
try
{
System.Diagnostics.Debug.WriteLine("Email: " + email);
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:49205/api/Account/Register", content);
if (response.IsSuccessStatusCode)
{
return true;
}
return false;
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Error: " + e);
throw;
}
}
如果我使用本地主机,则例外:
{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error: ConnectFailure (Connection refused) ---> System.Net.Sockets.SocketException: Connection refused
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x000b6] in <bcdc1df2b3724ab69797f3819a126346>:0
at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x0016d] in <bcdc1df2b3724ab69797f3819a126346>:0 --- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetRequestStream (System.IAsyncResult asyncResult) [0x0003a] in <bcdc1df2b3724ab69797f3819a126346>:0
at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <fcbf47a04b2e4d90beafbae627e1fca4>:0
如果我使用 10.0.2.2,则请求错误:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent,
Headers: {Server: Microsoft-HTTPAPI/2.0 Date: Thu, 17 May 2018 09:08:41 GMT Connection: close Content-Type: text/html; charset=us-ascii Content-Length: 334 }}