How to set Content-Type header for HttpClient request in C#?
Hi everyone! I'm new to C# and trying to send a POST request using HttpClient. I need to set the content type as application/json, but I can't figure out how to do it correctly. I've tried different ways, but I'm getting 400 Bad Request errors from the server.
Here's my current code:
```csharp
using (var client = new HttpClient())
{
var data = new { Name = "Test", Value = 123 };
var json = JsonSerializer.Serialize(data);
// Trying to set Content-Type
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
var response = await client.PostAsync("https://api.example.com/data",
new StringContent(json));
}
```
But when I run this code, I get an exception: "Misused header name. Ma
No answers yet.
Log in to leave an answer