Home > Back-end >  HttpClient headers vs HttpContent headers
HttpClient headers vs HttpContent headers

Time:03-01

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);

CodePudding user response:

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.

  • Related