HttpHeaders Class
Declares: System.Net.Http
Assembly: System.Net.Http.dll
Assembly: System.Net.Http.dll
Represents the collection of HTTP headers in a request or response.
Syntax
public sealed class HttpHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>>, IEnumerable
Fields
This class has no fields.
Properties
| Name | Description |
|---|---|
Count |
Gets the number of elements contained in the HttpHeaders collection. |
Methods
| Name | Description |
|---|---|
Add(string name, string value) |
Adds an HTTP header with the specified name and value. |
Clear() |
Removes all HTTP headers from the collection. |
Contains(string name) |
Determines whether the collection contains an HTTP header with the specified name. |
GetEnumerator() |
Returns an enumerator that iterates through the HttpHeaders collection. |
Remove(string name) |
Removes the HTTP header with the specified name from the collection. |
TryAddWithoutValidation(string name, string value) |
Adds an HTTP header with the specified name and value without validation. |
TryGetValue(string name, out IEnumerable<string> values) |
Tries to get the HTTP header values for the specified header name. |
Remarks
The HttpHeaders class provides a way to programmatically access and manipulate the headers associated with an HTTP request or response. Headers are represented as key-value pairs, where the key is the header name (e.g., "Content-Type", "User-Agent") and the value is typically a string or a collection of strings representing the header's value(s).
Examples
// Example of adding and retrieving headers
var request = new HttpRequestMessage(HttpMethod.Get, "https://example.com");
// Add a custom header
request.Headers.Add("X-My-Custom-Header", "SomeValue");
// Add multiple values for a header (e.g., Accept)
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Accept", "text/plain");
// Get all headers
Console.WriteLine("All Headers:");
foreach (var header in request.Headers)
{
Console.WriteLine($"{header.Key}: {string.Join(", ", header.Value)}");
}
// Try to get a specific header
if (request.Headers.TryGetValue("X-My-Custom-Header", out var customHeaderValue))
{
Console.WriteLine($"\nCustom Header Value: {string.Join(", ", customHeaderValue)}");
}
// Remove a header
request.Headers.Remove("Accept");
Console.WriteLine("\nHeaders after removing Accept:");
foreach (var header in request.Headers)
{
Console.WriteLine($"{header.Key}: {string.Join(", ", header.Value)}");
}
Note: The
HttpHeaders class is immutable once associated with a request or response. Modifications should be performed on a new instance or by obtaining a modifiable collection if available through specific methods.
Requirements
Namespace: System.Net.Http
Assembly: System.Net.Http.dll