HttpClient POST or PUT Json with content type application/json
By FoxLearn 1/9/2025 2:17:07 AM 119
It operates quite differently from the older WebRequest class. One key difference is how the content type is managed.
With HttpClient
, the content type is specified directly in the body of the request (through StringContent
), rather than as a header parameter. This is important if you're sending data like JSON with a POST
or PUT
request, as you'll need to explicitly set the content type in the StringContent
object.
Here’s how you can send JSON data with the correct content type:
string json; var content = new StringContent( json, System.Text.Encoding.UTF8, "application/json" );
Now, let’s look at a practical example of a POST
method that takes an object, serializes it into JSON, and sends it to a server:
using System.Net.Http; using Newtonsoft.Json; using System.Threading.Tasks; private static readonly HttpClient _httpClient = new HttpClient(); public async Task<bool> PostJsonDataAsync(object data, string url) { var jsonContent = JsonConvert.SerializeObject(data); using (var content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json")) { // Perform asynchronous POST request HttpResponseMessage response = await _httpClient.PostAsync(url, content); if (response.IsSuccessStatusCode) { // Check if the status code is 201 Created if (response.StatusCode == System.Net.HttpStatusCode.Created) return true; } // Read and throw detailed error if not successful string errorDetails = await response.Content.ReadAsStringAsync(); throw new HttpRequestException($"Failed to POST data: ({response.StatusCode}): {errorDetails}"); } }
In this example, the method serializes an object into JSON using JsonConvert.SerializeObject
, then sends it via a POST
request.
Note that we are not leveraging the asynchronous nature of HttpClient
here, which would be a more efficient approach in real-world scenarios.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#