post json data httpclient c# code example

Example 1: c# httpclient post json stringcontent

private static async Task PostBasicAsync(object content, CancellationToken cancellationToken)
{
    using (var client = new HttpClient())
    using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
    {
        var json = JsonConvert.SerializeObject(content);
        using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
        {
            request.Content = stringContent;

            using (var response = await client
                .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
                .ConfigureAwait(false))
            {
                response.EnsureSuccessStatusCode();
            }
        }
    }
}

Example 2: httpclient post c# json

var httpClient = new HttpClient();
  var json = JsonConvert.SerializeObject(ticket);
  var content = new StringContent(json, Encoding.UTF8, "application/json");
  await httpClient.PostAsync("https://address.com", content);