System.Net.Http.Headers

IntParsingHeaderParser

Parses integer values within HTTP headers. This internal helper class is used by various header parsers to correctly interpret numerical data in HTTP headers, ensuring compliance with RFC specifications.

Syntax

internal static class IntParsingHeaderParser

Remarks

This class is an internal implementation detail of the .NET HTTP headers parsing mechanism. It is not intended for direct use by application developers. Its primary role is to provide robust parsing of integer-like header values, handling potential whitespace and overflow scenarios.

Methods

TryParseInt(string value, out int result)

Attempts to parse an integer value from a given string.

public static bool TryParseInt(string value, out int result)
Parameter Type Description
value string The string to parse.
result out int When this method returns, contains the parsed integer value, if the parse succeeded, or 0 otherwise.

This method is crucial for handling HTTP headers that require integer values, such as Content-Length or Retry-After. It automatically trims leading and trailing whitespace and checks for valid integer formats.

ParseInt(string value)

Parses an integer value from a given string. Throws an exception if parsing fails.

public static int ParseInt(string value)
Parameter Type Description
value string The string to parse.

This overload provides a simpler way to parse if the caller expects the value to always be a valid integer and is prepared to handle potential exceptions.

Example Usage

using System;
using System.Net.Http.Headers;

public class Example
{
    public static void Main()
    {
        // Using TryParseInt
        string contentLengthValue = "  1024  ";
        int contentLength;

        if (IntParsingHeaderParser.TryParseInt(contentLengthValue, out contentLength))
        {
            Console.WriteLine($"Parsed Content-Length: {contentLength}"); // Output: Parsed Content-Length: 1024
        }
        else
        {
            Console.WriteLine("Failed to parse Content-Length.");
        }

        // Using ParseInt (can throw FormatException)
        string retryAfterValue = "60";
        try
        {
            int retryAfter = IntParsingHeaderParser.ParseInt(retryAfterValue);
            Console.WriteLine($"Parsed Retry-After: {retryAfter}"); // Output: Parsed Retry-After: 60
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid format for Retry-After header.");
        }
    }
}
                    

Requirements

Namespace: System.Net.Http.Headers
Assembly: System.Net.Http.Headers.dll