【问题标题】:Xamarin App cannot call APIs on LocalHostXamarin 应用程序无法调用 LocalHost 上的 API
【发布时间】:2023-03-03 15:23:01
【问题描述】:

我在从 Xamarin Android 应用调用 ASP.NET 核心 API 时遇到问题。 我在 android 模拟器上运行 android 应用程序,我在本地机器上运行 API。我从本地机器调用 api 没有问题,所以我知道它可以工作。我还可以从 Xamarin 应用程序调用其他 api。我正在使用 IP 地址 10.0.2.2 路由到我的本地计算机。但我无法成功地对本地机器上运行的 API 进行任何 API 调用。

这是我的 MainPage.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="APICallerTest.MainPage">
    <StackLayout>
        <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
            <Label Text="API Caller Test" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
        </Frame>
        <StackLayout Padding="30,24,30,0">
            <Button x:Name="CallAPIButton" VerticalOptions="Center" Text="Call API" Clicked="CallAPIButton_Clicked"/>
            <Label x:Name="CalledLabel"></Label>
            <Label x:Name="ResultLabel"></Label>
            <Label x:Name="ErrorLabel"></Label>
            <Label x:Name="StackTraceLabel"></Label>
        </StackLayout>
    </StackLayout>
</ContentPage>

这是我的 MainPage.xaml.cs:

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace APICallerTest
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private async Task CallAPI()
        {
            ResultLabel.Text = "";
            ErrorLabel.Text = "";
            StackTraceLabel.Text = "";

            try
            {
                string uri = "http://10.0.2.2:57817/Weatherforecast";

                HttpClient httpClient = new HttpClient();
                HttpResponseMessage httpResponse = await httpClient.GetAsync(uri);

                if (httpResponse.IsSuccessStatusCode)
                {
                    string result = await httpResponse.Content.ReadAsStringAsync();
                    ResultLabel.Text = $"Result: {result}";
                }
                else
                {
                    ResultLabel.Text = "Result: failed";
                }
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = $"Error Message: {ex.Message}";
                StackTraceLabel.Text = $"Stack Trace: {ex.StackTrace}";
            }
        }

        private void CallAPIButton_Clicked(object sender, EventArgs e)
        {
            CalledLabel.Text = "Called";
            CallAPI();
        }
    }
}

这是我的 api 在邮递员上的样子:

【问题讨论】:

  • 这是一个网络问题。您需要确保可以从设备访问您的机器 - 尝试使用设备上的浏览器进行测试。还要检查本地防火墙设置,如果您使用的是 VS 网络服务器,请确保将其配置为允许远程连接
  • 看看你的 Startup.cs(或者另一个,我总是忘记...)它听 0.0.0.0 吗?这也需要让它接受来自外部的请求,而不仅仅是 localhost
  • @Jason 是的,这一定与我的网络有关。目前,我刚刚将我的 API 发布到 azure 以通过这种方式访问​​它。

标签: c# xamarin xamarin.forms xamarin.android


【解决方案1】:

感谢这个问题,我能够解决这个问题: The SSL connection could not be established

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace APICallerTest
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private async Task CallAPI()
        {
            ResultLabel.Text = "";
            ErrorLabel.Text = "";
            StackTraceLabel.Text = "";

            try
            {
                string uri = "http://10.0.2.2:57817/Weatherforecast";
                
                //++++++++++Added client handler here ++++++++++
                HttpClientHandler clientHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
                };
                HttpClient httpClient = new HttpClient(clientHandler);
                               

                HttpResponseMessage httpResponse = await httpClient.GetAsync(uri);

                if (httpResponse.IsSuccessStatusCode)
                {
                    string result = await httpResponse.Content.ReadAsStringAsync();
                    ResultLabel.Text = $"Result: {result}";
                }
                else
                {
                    ResultLabel.Text = "Result: failed";
                }
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = $"Error Message: {ex.Message}";
                StackTraceLabel.Text = $"Stack Trace: {ex.StackTrace}";
            }
        }

        private void CallAPIButton_Clicked(object sender, EventArgs e)
        {
            CalledLabel.Text = "Called";
            CallAPI();
        }
    }
}

不过,一位用户指出,这确实会让您面临可能的安全风险。我认为它应该可以用于测试目的。

【讨论】:

  • 哦,这太容易了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
相关资源
最近更新 更多