Send JSON with HttpClient and handle unsuccessful responses

Use HttpClient.PostAsJsonAsync to serialize a request object as JSON and send it asynchronously. Then inspect the response status before treating its body as a successful result. A completed HTTP exchange can still return a 400 or 500 response.

This example uses an in-memory message handler so you can exercise success and failure paths without a remote service. The client code uses ordinary HTTP APIs. The handler is a test seam, not a real network server, and its successful execution does not test DNS, TLS or remote availability.

Run the client and controlled handler

Create a .NET 10 console project with dotnet new console -n PostDemo -f net10.0. Replace Program.cs and run dotnet run --project PostDemo from the parent directory. No additional package is required.

C#
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;

using var client = new HttpClient(new DemoHandler()) {
	BaseAddress = new Uri("https://api.example.test/")
};
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10));
using (var response = await client.PostAsJsonAsync("orders", new CreateOrder("Pencil", 2), deadline.Token)) {
	response.EnsureSuccessStatusCode();
	var result = await response.Content.ReadFromJsonAsync<OrderReceipt>(cancellationToken: deadline.Token)
		?? throw new InvalidOperationException("Missing receipt.");
	Console.WriteLine($"Created {result.Id}, HTTP {(int)response.StatusCode}");
}

using (var response = await client.PostAsJsonAsync("reject", new CreateOrder("Pencil", 0), deadline.Token)) {
	try {
		response.EnsureSuccessStatusCode();
	} catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.BadRequest) {
		Console.WriteLine($"Rejected request, HTTP {(int)response.StatusCode}");
	}
}

sealed record CreateOrder(string Product, int Quantity);
sealed record OrderReceipt(int Id);

sealed class DemoHandler : HttpMessageHandler {
	protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
		if (request.Method != HttpMethod.Post || request.Content is null) {
			throw new InvalidOperationException("Expected a POST body.");
		}
		var body = await request.Content.ReadFromJsonAsync<CreateOrder>(cancellationToken: cancellationToken)
			?? throw new InvalidOperationException("Missing order.");
		Console.WriteLine($"{request.Method} {request.RequestUri!.AbsolutePath} {request.Content.Headers.ContentType!.MediaType}");
		if (body.Quantity <= 0) {
			return new HttpResponseMessage(HttpStatusCode.BadRequest) {
				Content = JsonContent.Create(new { error = "Quantity must be positive." })
			};
		}
		return new HttpResponseMessage(HttpStatusCode.Created) {
			Content = JsonContent.Create(new OrderReceipt(101))
		};
	}
}

Expected output:

Plain text
POST /orders application/json
Created 101, HTTP 201
POST /reject application/json
Rejected request, HTTP 400

Adapt it to a real endpoint

Replace the controlled handler with your application's configured client and use the actual HTTPS base address. Match the endpoint's request schema, authentication mechanism and expected response statuses. Keep credentials in the application's secret configuration, never in source examples or diagnostic logs.

PostAsJsonAsync uses web-oriented JSON defaults unless you supply explicit options. A service with different names, enum conventions or date formats needs matching serializer settings. Successful deserialization also does not establish that every business field is valid.

Reuse a long-lived client with an appropriate pooled connection lifetime, or obtain clients through IHttpClientFactory. Do not create and dispose a fresh connection pool for each production request. This short-lived console demonstration owns one client for its whole run and disposes each response after reading it.

Distinguish failure modes

EnsureSuccessStatusCode throws for a non-success status. If your API returns a structured error body, inspect a bounded amount of that body before raising or translating the failure. Avoid logging arbitrary response content that may include personal data or secrets.

A network failure can throw before a response exists. Cancellation and timeouts can surface as OperationCanceledException, while malformed response JSON produces a serialization error. Handle each at the boundary that can make a meaningful decision. The shared token here imposes a ten-second budget on the entire two-request demonstration, including body reads.

Do not automatically retry a POST simply because the connection failed. The server may have committed the operation before its response was lost. Use the API's documented idempotency mechanism when retries are necessary, and verify that behavior with integration tests against a controlled real endpoint.

References

HttpClient guidelines for .NET - .NET
Learn about using HttpClient instances to send HTTP requests and how you can manage clients using IHttpClientFactory in your .NET apps.
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines
HttpClientJsonExtensions.PostAsJsonAsync Method (System.Net.Http.Json)
Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.json.httpclientjsonextensions.postasjsonasync?view=net-10.0
HttpResponseMessage.EnsureSuccessStatusCode Method (System.Net.Http)
Throws an exception if the IsSuccessStatusCode property for the HTTP response is false.
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpresponsemessage.ensuresuccessstatuscode?view=net-10.0
Make HTTP requests with the HttpClient - .NET
Learn how to make HTTP requests and handle responses with the HttpClient in .NET.
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient

Question provenance

This article addresses Send HTTP POST request in .NET , asked by Hooch on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored for current .NET. No answer text or code is reproduced.

Author: Herman Schoenfeld