简体   繁体   中英

How to connect API to my project in WPF .Net Core 3.1

I have API with link

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

and following is my model class

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; }
}
}

I want to connect my API to the .Net project and store the data from api in a list so that it can be use later in the project later such as listview to select any server to connect VPN and showing country name,city, pingrate and more.

There are number of ways to achieve this, and this approach requires no additional dependencies.

obj will be the results deserialized into the ServerModel class.

 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);   
 }

To then bind these results to a ListView you can use the following code, however I think a DataGrid might be more suited to display multiple columns etc.

lvwServer.ItemsSource = obj.servers;
lvwServer.DisplayMemberPath = "dns"; //Or another property of Server you want to display

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM