HttpResponseHeaders Class
Namespace: System.Net.Http.Headers
Assembly: System.Net.Http.dll
Represents the collection of HTTP headers associated with an HTTP response.
Syntax
public sealed class HttpResponseHeaders : HttpHeaders
Inheritance
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
-
Connection
get;
Gets or sets the connection headers.
-
ContentMD5
get;
Gets or sets the Content-MD5 header.
-
ContentType
get;
Gets or sets the Content-Type header.
-
Date
get;
Gets or sets the Date header.
-
Location
get;
Gets or sets the Location header.
-
TransferEncoding
get;
Gets or sets the Transfer-Encoding header.
-
UserAgent
get;
Gets or sets the User-Agent header.
Methods
-
AddWithoutValidation
(string name, IEnumerable<string> values)
Adds a header without validating the header name or its values.
-
Contains
(string name)
Determines whether the specified header name exists in the collection.
-
GetValues
(string name)
Gets the values for the specified header name.
-
Remove
(string name)
Removes the specified header from the collection.
-
TryAddWithoutValidation
(string name, IEnumerable<string> values)
Tries to add a header without validating the header name or its values.
-
TryGetValue
(string name, out IEnumerable<string> values)
Tries to get the values for the specified header name.
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");