c# - 如何在 WPF .Net Core 3.1 中将 API 连接到我的项目
问题描述
我有带链接的 API
以下是我的模型课
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VPN.Model
{
public class ServerModel
{
public string error { get; set; }
public string message { get; set; }
public Server[] servers { get; set; }
}
public class Server
{
public string sid { get; set; }
public string country { get; set; }
public string dns { get; set; }
public string port { get; set; }
public string psk { get; set; }
public string pptp { get; set; }
public string l2tp { get; set; }
public string tcp { get; set; }
public string udp { get; set; }
public string openconnect { get; set; }
public string ikev2 { get; set; }
public string sstp { get; set; }
public string p2p { get; set; }
public string videostreaming { get; set; }
public string security { get; set; }
public string voip { get; set; }
public string enable { get; set; }
public string maintmode { get; set; }
public string iso { get; set; }
public string free { get; set; }
public string recent { get; set; }
public string time { get; set; }
public string fav { get; set; }
public int Pingrate { get; set; }
public string IsFavorite { get; set; }
public string FavProtocol { get; set; }
}
}
我想将我的 API 连接到 .Net 项目并将来自 api 的数据存储在一个列表中,以便稍后在项目中使用它,例如 listview 选择任何服务器来连接 VPN 并显示国家名称、城市、pingrate 和更多的。
解决方案
有很多方法可以实现这一点,并且这种方法不需要额外的依赖项。
obj 将结果反序列化到 ServerModel 类中。
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://webservice.casvpn.com/");
HttpResponseMessage response = client.GetAsync("serverlist.php").Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
var obj = System.Text.Json.JsonSerializer.Deserialize<ServerModel>(result);
}
然后将这些结果绑定到 ListView 您可以使用以下代码,但是我认为 DataGrid 可能更适合显示多列等。
lvwServer.ItemsSource = obj.servers;
lvwServer.DisplayMemberPath = "dns"; //Or another property of Server you want to display
推荐阅读
- java - 使用 java 和 jsoup从网站上的标签中提取 src 值
- vb.net - 错误:无法为输出文件 #0 写入标头(编解码器参数不正确?):参数无效
- python - get() 接受 2 到 3 个位置参数,但给出了 4 个。为什么会出现这个错误?解决方案是什么?
- python - 如何提取
- java - 当定义的对象已经存在于地图中时,从我的地图中获取空返回值?
- mysql - 根据某天的两列从 MySQL DB 中删除每日重复项
- angular - 网格系统没有按预期工作,手机屏幕的宽度远小于最小尺寸的浏览器
- python - get_schedule (get_availability) 与 python api O365
- javascript - getRandomInt 总是返回 0
- php - Php Array - JSON 结构 - 推送数据