public HttpResponseHeaders Content.Headers { get; }
Gets the collection of HTTP content headers associated with the response.
This property provides access to the HttpResponseHeaders object, which allows you to read and manipulate various HTTP headers related to the response's content. These headers provide important metadata about the response body, such as its type, size, and encoding.
The Content.Headers property returns an object of type HttpResponseHeaders. This object is a dictionary-like collection where keys are header names (case-insensitive) and values are the corresponding header values.
Commonly used headers accessible through this property include:
Content-Type: Indicates the media type of the resource.Content-Length: The size of the response body in bytes.Content-Encoding: The compression algorithm used for the response body.Expires: The date and time after which the response is considered stale.Cache-Control: Directives for caching mechanisms.You can use extension methods provided by the .NET library to easily add or retrieve specific header values.
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; public class Example { public static async Task DemonstrateContentHeaders() { using (var client = new HttpClient()) { try { HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1"); response.EnsureSuccessStatusCode(); // Throw if the status code is an error // Accessing the Content-Type header MediaTypeHeaderValue contentType = response.Content.Headers.ContentType; if (contentType != null) { Console.WriteLine($"Content-Type: {contentType.MediaType}"); if (contentType.CharSet != null) { Console.WriteLine($" Charset: {contentType.CharSet}"); } } // Accessing the Content-Length header long? contentLength = response.Content.Headers.ContentLength; if (contentLength.HasValue) { Console.WriteLine($"Content-Length: {contentLength.Value} bytes"); } // Getting all content headers Console.WriteLine("\nAll Content Headers:"); foreach (var header in response.Content.Headers) { Console.WriteLine($"{header.Key}: {string.Join(", ", header.Value)}"); } // You can also add headers to the request before sending, // but this example focuses on reading response headers. } catch (HttpRequestException e) { Console.WriteLine($"An error occurred: {e.Message}"); } } } }