ProductHeaderValue

System.Net.Http.Headers

Represents a product header value. A product header value is a name-value pair that identifies a product and optionally its version.

Inheritance

Constructors

ProductHeaderValue(string product)
Initializes a new instance of the ProductHeaderValue class.
ProductHeaderValue(string product, string version)
Initializes a new instance of the ProductHeaderValue class with a product name and version.

Properties

string Product
Gets the name of the product.
string Version
Gets the version of the product.

Methods

static ProductHeaderValue Parse(string input)
Parses a product header value from the specified string.
static bool TryParse(string input, out ProductHeaderValue? value)
Determines whether the string is a valid product header value.
override string ToString()
Returns a string that represents the current object.
override bool Equals(object? obj)
Indicates whether the current object is equal to another object of the same type.
override int GetHashCode()
Returns the hash code for this instance.

Remarks

The ProductHeaderValue class is used to represent the User-Agent header, as well as other product-related headers, in HTTP requests.

It consists of a product name and an optional version. For example, a User-Agent header could be represented as:


User-Agent: MyAwesomeApp/1.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36

In this example, MyAwesomeApp is the product name and 1.0 is the version.

Example Usage


using System.Net.Http.Headers;

public class Example
{
    public static void Main(string[] args)
    {
        // Create a ProductHeaderValue
        ProductHeaderValue productInfo = new ProductHeaderValue("MyClient", "1.2.3");
        Console.WriteLine($"Product: {productInfo.Product}, Version: {productInfo.Version}");
        Console.WriteLine($"String representation: {productInfo.ToString()}");

        // Using Parse
        string headerString = "MyServer/2.0";
        if (ProductHeaderValue.TryParse(headerString, out ProductHeaderValue? parsedProduct))
        {
            Console.WriteLine($"Parsed Product: {parsedProduct.Product}, Version: {parsedProduct.Version}");
        }
        else
        {
            Console.WriteLine($"Failed to parse: {headerString}");
        }

        // Setting User-Agent header
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.UserAgent.Add(productInfo);
            // Now client requests will include User-Agent: MyClient/1.2.3
        }
    }
}