尝试连接到本地主机服务器时 Xamarin.forms Mac 连接被拒绝

问题描述

在我的项目中,我必须反序列化必须从本地主机服务器获取的对象产品列表。然而,每次我尝试使用 HttpClient() 获取该数据时,我都会收到连接被拒绝的异常,这会导致另一个异常,因为现在我有一个空列表。

我可以在我的本地主机(https://localhost:5002/controller/Getall)中看到序列化列表,我只是想将这个列表从 API 反序列化到我的应用程序。

消息是:连接被拒绝,e.getBaseExeption 是:Java.Net.ConnectionExecption

我怎样才能让我的连接真正连接起来?

应用程序中的 App.xaml.cs

public App()
        {
            InitializeComponent();

            var handler = new WebRequestHandler();
            try
            {
                
                List<Product> test = JsonConvert.DeserializeObject<List<Product>>(handler.Get("https://localhost:5002/controller/GetAll").Result);
                foreach (Product x in test)
                {
                    Console.WriteLine(x.Name);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("e message: " + e.Message);
            }

应用程序中的WebRequestHandler

public class WebRequestHandler
    {
        private HttpClient Client { get; }
        public WebRequestHandler()
        {
            Client = new HttpClient();
        }
        public async Task<string> Get(string url)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    var response = await client.GetStringAsync(url).ConfigureAwait(false);
                    return response;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + " " + e.GetBaseException());
               
            }


            return null;
        }

        public async Task<string> Post(string url,object obj)
        {
            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Post,url))
                {
                    var json = JsonConvert.SerializeObject(obj);
                    using (var stringContent = new StringContent(json,Encoding.UTF8,"application/json"))
                    {
                        request.Content = stringContent;

                        using (var response = await client
                            .SendAsync(request,HttpCompletionoption.ResponseHeadersRead)
                            .ConfigureAwait(false))
                        {
                            if (response.IsSuccessstatusCode)
                            {
                                return await response.Content.ReadAsstringAsync();
                            }
                            return "ERROR";
                        }
                    }
                }
            }
        }
    }

InventoryController

[ApiController]
    [Route("Controller")]
    public class InventoryController : ControllerBase
    { 

        [HttpGet("GetAll")]
        public ActionResult<List<Product>> Get()
        {
            return Ok(DataContext.Inventory);
        }

    }

DataContext.cs

public class DataContext
    {
            public static List<Product> Inventory = new List<Product>
            {
                new ProductByQuantity(2.00,20,"Ketchup","Canned & Packaged Foods",0002),new ProductByQuantity(2.00,35,"Mayonnaise",0003),new ProductByQuantity(5.00,25,"Chocolate bar",0004),new ProductByQuantity(3.50,100,"Paper Towels","Miscellaneous Kitchen Items",0005),new ProductByQuantity(2.35,80,"Plastic Wrap",0006),new ProductByQuantity(1.50,90,"Yougurt","Refrigerated Foods",0007),new ProductByQuantity(1.25,150,"Bagels","Bakery",0008),new ProductByQuantity(1.00,200,"Bread",0009),45,"Cereal","Breakfast",0010),};
    }

解决方法

你必须记住 localhost 指的是手头的机器。在这种情况下,如果您说 localhost:5002,您是在告诉设备转到端口 5002 并转到那个当然不存在的 URL。

您需要的是像 ngrok (https://ngrok.com/) 这样的隧道。这种方式不是调用 localhost,而是传递在托管 API 的机器上运行的 ngrok url,这样它就会使 localhost API 对外界可见。

但是,如果它是 Android(我问是因为我看到您提到了 Java 的异常),如果您使用 10.0.2.2(如果那个不起作用,请尝试 0.0.0.0)这是本地回调它如果您使用该 IP,它应该能够连接到您的本地主机。

再说一次,首选的方法是某种隧道