且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#在POST请求中发送JSON数据

更新时间:2022-05-16 07:58:22

您可以使用

You can use the HttpClient instead of the WebClient and HttpWebRequest. It's a newer implementation.

string myJson = "{'Username': 'myusername','Password':'pass'}";
using (var client = new HttpClient())
{
    var response = await client.PostAsync(
        "http://yourUrl", 
         new StringContent(myJson, Encoding.UTF8, "application/json"));
}

如果您需要更多HttpClient,则建议仅创建一个实例并重用它或使用新的HttpClientFactory.

When you need your HttpClient more then once it's recommended to only create one instance and reuse it or use the new HttpClientFactory.