make a http request with a custom body as json in csharp

To make a HTTP request with a custom body as JSON in C#, you can use the HttpClient class from the System.Net.Http namespace. The following code snippet shows an example of how to make a POST request with a JSON body:

main.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace MyApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var httpClient = new HttpClient();
            var uri = new Uri("https://my-api.com/my-endpoint");
            var requestBody = new { Property1 = "Value1", Property2 = "Value2" };
            var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");

            var response = await httpClient.PostAsync(uri, content);

            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseContent);
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode}");
            }
        }
    }
}
892 chars
30 lines

In this example, we create an instance of the HttpClient class and set the URI of the API endpoint we want to send the request to. The requestBody variable contains the data we want to send in the request body, and we serialize it to JSON using JsonConvert.SerializeObject from the Newtonsoft.Json package. We create a StringContent instance from the serialized JSON and set its MediaType property to application/json. Finally, we use the PostAsync method of the HttpClient instance to send the POST request with the JSON body to the API endpoint. If the API returns a success status code, we read and print the response body. Otherwise, we print an error message with the status code of the response.

gistlibby LogSnag