NameValueHeaderValue Class
Represents a name-value pair that is used in HTTP headers.
Namespace
System.Net.Http.Headers
Assembly
System.Net.Http.Headers.dll
Syntax
public class NameValueHeaderValue
Constructors
NameValueHeaderValue(string name)
Initializes a new instance of the NameValueHeaderValue class with the specified header name.
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | The name of the header. |
NameValueHeaderValue(string name, string value)
Initializes a new instance of the NameValueHeaderValue class with the specified header name and value.
Parameters
| Name | Type | Description |
|---|---|---|
name |
string | The name of the header. |
value |
string | The value of the header. |
Properties
Name
Gets the name of the header.
public string Name { get; }
Value
Gets or sets the value of the header.
public string Value { get; set; }
Methods
Equals(object obj)
Determines whether the specified object is equal to the current object.
Parameters
| Name | Type | Description |
|---|---|---|
obj |
object | The object to compare with the current object. |
Returns
bool: true if the specified object is equal to the current object; otherwise, false.
GetHashCode()
Serves as the default hash function.
Returns
int: A hash code for the current object.
ToString()
Returns a string that represents the current object.
Returns
string: A string that represents the current object.
Examples
Creating a NameValueHeaderValue
The following code example shows how to create a NameValueHeaderValue object and add it to the Headers collection of an HttpRequestMessage.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
public class Example
{
public static void Main()
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://www.example.com");
// Create a NameValueHeaderValue
var customHeader = new NameValueHeaderValue("X-My-Header", "MyValue");
request.Headers.Add(customHeader.Name, customHeader.Value);
// You can also add headers without a value
var anotherHeader = new NameValueHeaderValue("X-Another-Header");
request.Headers.Add(anotherHeader.Name, anotherHeader.Value); // Value will be null here
Console.WriteLine($"Request headers count: {request.Headers.Count()}");
foreach (var header in request.Headers)
{
Console.WriteLine($"{header.Key}: {header.Value.ToString()}");
}
}
}