HttpResponseHeaders Class

Assembly: System.Net.Http.dll

Represents the collection of HTTP headers associated with an HTTP response.

Syntax

public sealed class HttpResponseHeaders : HttpHeaders

Inheritance

Inheritance diagram for HttpResponseHeaders

Remarks

The HttpResponseHeaders class is used to access the headers that are sent with an HTTP response. The HttpResponseMessage.Headers property returns an instance of this class.

You can use this class to retrieve or modify specific headers, such as Content-Type, Cache-Control, or custom headers.

Properties

Methods

Examples

Accessing Response Headers

The following example demonstrates how to get the Content-Type header from an HttpResponseMessage:

using System.Net.Http;
using System.Net.Http.Headers;

// Assume 'response' is an HttpResponseMessage object obtained from an HTTP request

if (response.Headers.TryGetValues("Content-Type", out IEnumerable<string> contentTypeValues))
{
    Console.WriteLine($"Content-Type: {string.Join(",", contentTypeValues)}");
}

// Accessing specific strongly-typed headers
MediaTypeHeaderValue contentType = response.Content.Headers.ContentType;
if (contentType != null)
{
    Console.WriteLine($"Content-Type (parsed): {contentType.MediaType}");
}

Adding Custom Headers

While HttpResponseHeaders is primarily for response headers, you can add custom headers:

using System.Net.Http;
using System.Net.Http.Headers;

// Assume 'response' is an HttpResponseMessage object

response.Headers.Add("X-Custom-Header", "MyValue");

// Or to add multiple values for the same header
response.Headers.Add("X-Another-Header", new string[] { "Value1", "Value2" });

// Using TryAddWithoutValidation for headers with potentially invalid characters (use with caution)
response.Headers.TryAddWithoutValidation("X-Problematic-Header", "Some Value; Comment");