InvalidHeaderException

Represents errors that occur when an invalid header is encountered in an HTTP message.

Syntax

public sealed class InvalidHeaderException : FormatException

Constructors

Name Description
InvalidHeaderException() Initializes a new instance of the InvalidHeaderException class.
InvalidHeaderException(string message) Initializes a new instance of the InvalidHeaderException class with a specified error message.
InvalidHeaderException(string message, Exception innerException) Initializes a new instance of the InvalidHeaderException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Usage

This exception is typically thrown by the System.Net.Http.Headers namespace when parsing or validating HTTP headers fails. This can happen if a header value does not conform to the expected format according to RFC specifications.

For example, attempting to add a header with an invalid character or an incorrectly formatted value might result in this exception.

try
{
    // Attempt to add an invalid header value
    var request = new HttpRequestMessage();
    request.Headers.Add("X-Custom-Header", "Invalid Value!"); // This might throw
}
catch (InvalidHeaderException ex)
{
    Console.WriteLine($"An invalid header was encountered: {ex.Message}");
}

Exceptions

  • InvalidHeaderException: This exception is thrown when an invalid header is detected.
  • ArgumentNullException: If a null reference is passed to a constructor that requires a non-null argument.

Remarks

The InvalidHeaderException inherits from FormatException, indicating that the error is due to an incorrectly formatted string or value.

When handling this exception, it is often useful to examine the inner exception if one is provided, as it may contain more specific details about the cause of the formatting error.

Developers should ensure that all HTTP headers added programmatically conform to relevant RFC standards to avoid this exception. For common headers, the System.Net.Http.Headers namespace provides strongly-typed classes and methods that help enforce correct formatting.