HttpLibHeaderValue

Represents a header value that can be converted to and from a string.

This is a fundamental type for handling HTTP headers within the System.Net.Http namespace, providing a standardized way to parse and format header values.

Namespace

System.Net.Http.Headers

Class Declaration

public abstract class HttpLibHeaderValue

Introduction

The HttpLibHeaderValue class serves as an abstract base class for types that represent HTTP header values. It defines the essential contract for parsing header values from strings and formatting them back into strings.

Key Concepts

Common Implementations

Several concrete classes inherit from HttpLibHeaderValue to handle common HTTP header types:

Abstract Members

Subclasses must implement the following members:

public abstract bool TryParse(string value, out HttpLibHeaderValue result);

public abstract bool TryParse(string value, out HttpLibHeaderValue result)

Attempts to parse a string representation of a header value into an instance of a derived class.

Parameters

Returns

public abstract string ToString();

public abstract string ToString()

Converts the header value object back into its string representation.

Returns

Example Usage

Parsing a Content-Type header:

using System.Net.Http.Headers;

string contentTypeString = "application/json; charset=utf-8";
HttpLibHeaderValue parsedValue;

if (MediaTypeHeaderValue.TryParse(contentTypeString, out parsedValue))
{
    MediaTypeHeaderValue mediaType = (MediaTypeHeaderValue)parsedValue;
    Console.WriteLine($"Media Type: {mediaType.MediaType}"); // Output: application/json
    Console.WriteLine($"Char Set: {mediaType.CharSet}");     // Output: utf-8
    Console.WriteLine($"Formatted: {mediaType.ToString()}");  // Output: application/json; charset=utf-8
}
else
{
    Console.WriteLine("Failed to parse Content-Type header.");
}
        
Creating and formatting a header value:

using System.Net.Http.Headers;

var customHeader = new StringWithQualityHeaderValue("gzip");
string headerString = customHeader.ToString();
Console.WriteLine($"Custom Header: {headerString}"); // Output: gzip
        

Related Types

HttpHeaderValue<T>

public abstract class HttpHeaderValue<T> : HttpLibHeaderValue where T : HttpLibHeaderValue, new()

A generic abstract base class for typed header values. It simplifies the implementation of TryParse by providing a default mechanism to create new instances.

MediaTypeHeaderValue

public sealed class MediaTypeHeaderValue : HttpHeaderValue<MediaTypeHeaderValue>

Represents a media type header value, such as "text/html; charset=utf-8". Used for Content-Type and Accept headers.

Members

RangeUnitHeaderValue

public sealed class RangeUnitHeaderValue : HttpLibHeaderValue

Represents the unit used in a Range header, such as "bytes".

Members

TransferCodingHeaderValue

public abstract class TransferCodingHeaderValue : HttpLibHeaderValue

Abstract base class for transfer coding header values.

Example Implementations