在 C# winform 中获取数据 JSON

Get data JSON in C# winform

我想从这个 URL: "http://localhost/api/basic.php?id={ id}" 在 C#

我用这个代码得到

string api = "http://localhost/api/basic.php?id=";
api += TxtID.Text;
WebClient client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(api);
myHttpWebRequest.Referer = "http://localhost/api/form.html";

现代方式(对于 .net 5 和 4.x)是:

using System.Net.Http.Json;  // add the NuGet package

private HttpClient client = new HttpClient();
private async void MyForm_Load(object sender, EventArgs e)
{           
    MyClass data = await client.GetFromJsonAsync<MyClass>(api);
    ...
}

不处置 HttpClient。

包不是默认 WinForms 模板的一部分,从 NuGet 添加 System.Net.Http.Json