【发布时间】:2021-07-03 22:22:14
【问题描述】:
在我的项目中,我必须反序列化必须从 localhost 服务器获取的对象产品列表。但是,每次我尝试使用 HttpClient() 获取该数据时,都会收到一个连接被拒绝的异常,这会导致另一个异常,因为现在我有一个空列表。
我可以在我的 localhost(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";
}
}
}
}
}
}
库存控制器
[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", "Canned & Packaged Foods", 0003),
new ProductByQuantity(5.00, 25, "Chocolate bar", "Canned & Packaged Foods", 0004),
new ProductByQuantity(3.50, 100, "Paper Towels", "Miscellaneous Kitchen Items", 0005),
new ProductByQuantity(2.35, 80, "Plastic Wrap", "Miscellaneous Kitchen Items", 0006),
new ProductByQuantity(1.50, 90, "Yougurt", "Refrigerated Foods", 0007),
new ProductByQuantity(1.25, 150, "Bagels", "Bakery", 0008),
new ProductByQuantity(1.00, 200, "Bread", "Bakery", 0009),
new ProductByQuantity(3.50, 45, "Cereal", "Breakfast", 0010),
};
}
【问题讨论】:
-
你需要做一些基本的网络调试。您的设备可以使用浏览器访问服务器 url 吗?服务器是否设置为接收远程连接?你的防火墙打开了吗? SSL 配置是否正确?您是否尝试过使用 IP 而不是 localhost?
-
可以通过浏览器访问服务器。我想我做得对。我会看看其他建议,谢谢!
标签: c# xamarin xamarin.forms https