asp.net - 如何从android模拟器访问本地主机?

标签 asp.net asp.net-web-api xamarin.forms android-emulator localhost

我正在通过本教程学习 Xamarin - Signup user to ASP.NET Identity from Xamarin Forms .如果向 postman 发送请求,一切正常。但是如果我想使用 android 模拟器,它是行不通的。而且我不能使用 UWP,因为必须启用开发人员模式,而且我在公司计算机上没有管理员权限。我在我的私有(private)计算机上启用了开发人员模式,它可以在 UWP 上运行,但不能在 Android 模拟器上运行。教程中使用的是UWP,那家伙说Android模拟器需要一些配置,但他没有说出任何细节。

我读了很多文章,似乎问题出在我的后端(在本地主机上运行)和 android 模拟器之间的连接上。 android 模拟器是一台试图调用我的本地主机的独立机器是否正确?我尝试将 localhost 更改为 127.0.0.1 或 10.0.2.2,并尝试了 this article 中的所有选项.但它不起作用。

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

如果我使用本地主机则异常(exception):

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

最佳答案

localhost 是指您的本地计算机。一个常见的错误是人们认为 Android 模拟器(或 iOS)也是 localhost 的一部分,因为它们在同一台机器上运行。但事实并非如此。

模拟器在您的设备中作为一个设备运行,并模拟其工作方式,就好像它是一个物理设备一样。它有自己的 IP 地址,无法到达您的 localhost 环回地址。您的应用程序作为应用程序在另一台机器上运行,即 te emulator。使用 UWP 时会有点困惑,因为它确实作为应用程序在您的本地计算机上运行。

这就是为什么您必须使用托管服务器应用程序的机器的网络地址。此地址通常以 192.168.x.x10.x.x.x 开头,可以在您机器的网络设置中找到。

看来你已经发现了这一点。当使用 10.0.2.2 地址时,您会收到一个 HTTP 400。这意味着您的请求中的某些内容不正确,但您可以由此得出结论,实际上可以访问服务器应用程序。但是请求的内容会导致您的服务器应用程序出现问题。由于您没有为 /Account/Register 端点提供任何代码,因此无法判断那里发生了什么。在您的服务器代码中放置一个断点,重试请求并尝试查看触发 HTTP 400 的原因。

关于asp.net - 如何从android模拟器访问本地主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50389325/

相关文章:

javascript - 发布 500 错误 : axios behaves differently in two very similar but independent functions in asp.net React 应用程序

c# - 从 Tap (TapGestureRecognizer) 事件中提取 byte[] 到 Xamarin Forms 中的 Click 事件

angularjs - 通过 id 以及字符串 angularjs webapi 获取

asp.net-web-api - WebAPI 请求在同一请求上抛出 404 错误...

android - 如何使用 Xamarin 播放暂停音频

c# - Xamarin 网格和 StackLayout

javascript - 更改部分回发中的 URL

asp.net - 在 web.config 中重定向到 www 时忽略 IP

c# - 更新数据库中的值 - MVC

asp.net - AspxGridView 默认聚焦行