HttpHeaders Class
Represents the collection of HTTP headers for an HTTP message.
Namespace:
Inheritance:
object → HttpHeaders
Remarks:
The HttpHeaders class provides a way to access and manage the headers of an HTTP request or response. It is a dictionary-like collection where keys are header names (strings) and values are lists of header values. This class is typically used indirectly through HttpRequestHeaders and HttpResponseHeaders, which inherit from it and provide specific members for common HTTP headers.
Methods:
| Name | Description |
|---|---|
| Add(string name, IEnumerable<string> values) | Adds a new header to the collection. |
| Contains(string name) | Determines whether a header with the specified name exists in the collection. |
| GetValues(string name) | Retrieves the values of a specific header. |
| Remove(string name) | Removes a header from the collection. |
| TryGetValue(string name, out IEnumerable<string> values) | Attempts to retrieve the values of a specific header, returning `true` if successful. |
Properties:
| Name | Description |
|---|---|
| Count | Gets the number of headers in the collection. |
| Keys | Gets a collection of all header names in the collection. |
Example:
The following example demonstrates how to add and retrieve custom headers using HttpHeaders:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
public class HttpHeadersExample
{
public static void Main(string[] args)
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com");
// Accessing HttpRequestHeaders which inherits from HttpHeaders
HttpRequestHeaders headers = request.Headers;
// Adding a custom header
headers.Add("X-MyCustomHeader", "MyValue");
headers.Add("X-AnotherHeader", new string[] { "Value1", "Value2" });
// Checking if a header exists
if (headers.Contains("X-MyCustomHeader"))
{
Console.WriteLine("X-MyCustomHeader exists.");
}
// Getting header values
IEnumerable<string> customValues = headers.GetValues("X-MyCustomHeader");
Console.WriteLine("Values for X-MyCustomHeader:");
foreach (var value in customValues)
{
Console.WriteLine($"- {value}");
}
// Trying to get values that might not exist
IEnumerable<string> nonExistentValues;
if (headers.TryGetValue("NonExistentHeader", out nonExistentValues))
{
Console.WriteLine("Found NonExistentHeader (this should not happen).");
}
else
{
Console.WriteLine("NonExistentHeader not found.");
}
// Iterating through all headers
Console.WriteLine("\nAll Headers:");
foreach (var header in headers)
{
Console.WriteLine($"{header.Key}: {string.Join(", ", header.Value)}");
}
// Removing a header
if (headers.Remove("X-AnotherHeader"))
{
Console.WriteLine("\nX-AnotherHeader removed.");
}
}
}