HttpLifetimeHeaderValue Class

System.Net.Http.Headers

Represents a standard HTTP header value that specifies a time span for a resource's lifetime. This class is used to parse and represent values such as max-age or s-maxage in cache-related HTTP headers like Cache-Control.

Constructors

HttpLifetimeHeaderValue(TimeSpan)

Initializes a new instance of the HttpLifetimeHeaderValue class with the specified time span.

Properties

Offset

Gets or sets the time span represented by the header value.

Seconds

Gets the number of seconds represented by the header value.

Methods

Parse(String)

Parses a string representation of an HTTP lifetime header value.

TryParse(String, HttpLifetimeHeaderValue ByRef)

Attempts to parse a string representation of an HTTP lifetime header value.

ToString()

Converts the current HttpLifetimeHeaderValue object to its string representation.

Remarks

The HttpLifetimeHeaderValue class is designed to work with HTTP headers that specify a duration. For example, in the Cache-Control header, directives like max-age=3600 or s-maxage=7200 specify how long a resource should be cached. This class provides a structured way to handle these time-based values, converting them to and from TimeSpan objects and their string representations.

Example Usage


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

public class Example
{
    public static void Main(string[] args)
    {
        // Create a HttpLifetimeHeaderValue for 1 hour
        TimeSpan cacheDuration = TimeSpan.FromHours(1);
        HttpLifetimeHeaderValue maxAge = new HttpLifetimeHeaderValue(cacheDuration);

        Console.WriteLine($"Max-Age value: {maxAge}"); // Output: Max-Age value: 3600
        Console.WriteLine($"Max-Age in seconds: {maxAge.Seconds}"); // Output: Max-Age in seconds: 3600

        // Parse a string value
        string headerString = "7200";
        if (HttpLifetimeHeaderValue.TryParse(headerString, out HttpLifetimeHeaderValue sMaxAge))
        {
            Console.WriteLine($"Parsed s-maxage: {sMaxAge}"); // Output: Parsed s-maxage: 7200
            Console.WriteLine($"Parsed s-maxage as TimeSpan: {sMaxAge.Offset}"); // Output: Parsed s-maxage as TimeSpan: 02:00:00
        }
    }
}