首页 > 解决方案 > 如何在 WPF .Net Core 3.1 中将 API 连接到我的项目

问题描述

我有带链接的 API

https://webservice.sampleVPN.com/serverlist.php

以下是我的模型课

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 和更多的。

标签: c#wpfapi.net-core-3.1

解决方案


有很多方法可以实现这一点,并且这种方法不需要额外的依赖项。

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

推荐阅读