make a post requeset in csharp

To make a Post request in C#, we can use the HttpClient class provided by the .NET framework. Here's an example of how to make a Post request to a remote web server using HttpClient:

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

public static async Task<string> PostAsync(Uri uri, object requestBody)
{
    using (var client = new HttpClient())
    {
        var json = JsonSerializer.Serialize(requestBody);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(uri, content);
        
        return await response.Content.ReadAsStringAsync();
    }
}
477 chars
16 lines

In this example, we use the JsonSerializer class to serialize our request body to JSON. We then create a new instance of StringContent class with the serialized JSON, specifying the content type as application/json. Finally, we make the Post request with the PostAsync method of HttpClient, passing in the request URI and content.

Note that this example uses async and await, which allows the method to continue executing while waiting for the Post request to complete.

gistlibby LogSnag