0

In c# why both HttpClient and HttpContent have headers. What is difference between them. When should I use client headers and when content headers ?

CODE EXAMPLE:

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Test header", "content");

HttpContent content = new StringContent("text", Encoding.UTF8, "application/json");
content.Headers.Add("TestHeader", "Header Content");

await client.PostAsync("url", content);
  • The client headers are the headers that should be sent for every request by default. The content headers are headers that should only be sent for this specific content/request. – ckuri Mar 01 '22 at 17:53

1 Answers1

0

HttpClient supports several types of content. For example:

  • System.Net.Http.ByteArrayContent
  • System.Net.Http.Json.JsonContent
  • System.Net.Http.MultipartContent
  • System.Net.Http.ReadOnlyMemoryContent
  • System.Net.Http.StreamContent

For a complete list of supported content, see HttpContent.

HttpContent contains some more specific headers about the content, including the content type.

I think this list here can give you a pretty good understanding on what headers that are available. I do agree that having jus one set of headers would make things much easier.

Tore Nestenius
  • 16,431
  • 5
  • 30
  • 40