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

问题描述:

我想使用C#在POST请求中发送json数据.

I want to send json data in POST request using C#.

我尝试了几种方法,但是面临很多问题.我需要使用请求正文作为来自字符串的原始json和来自json文件的json数据进行请求.

I have tried few ways but facing lot of issues . I need to request using request body as raw json from string and json data from json file.

如何使用这两种数据形式发送请求.

How can i send request using these two data forms.

Ex:对于json中的身份验证请求正文-> {"Username":"myusername","Password":"pass"}

Ex: For authentication request body in json --> {"Username":"myusername","Password":"pass"}

对于其他API,请求主体应从外部json文件中检索.

For other APIs request body should retrieved from external json file.

您可以使用

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.