HttpPredicateHeaderValue

Summary

Represents a predicate that evaluates to true if a header value matches a specified condition.

.NET HTTP Headers System.Net.Http.Headers Predicate Header Value

Namespace: System.Net.Http.Headers

Assembly: System.Net.Http.dll

Constructors

HttpPredicateHeaderValue( string headerName, Func<string, bool> predicate )

Initializes a new instance of the HttpPredicateHeaderValue class with the specified header name and predicate.

HttpPredicateHeaderValue( string headerName, string headerValue )

Initializes a new instance of the HttpPredicateHeaderValue class with the specified header name and an exact header value to match.

Methods

bool Evaluate( string headerValue )

Evaluates the predicate against the given header value.

Parameters

Name Type Description
headerValue string The header value to evaluate.

Returns

true if the header value satisfies the predicate; otherwise, false.

Remarks

The HttpPredicateHeaderValue class is useful for scenarios where you need to conditionally process HTTP requests or responses based on the values of specific headers. For example, you might use it to check for the presence or specific format of headers like Accept, Content-Type, or custom headers.

The predicate function allows for flexible matching logic, going beyond simple equality checks. You can define complex rules based on string manipulation, regular expressions, or any other custom logic.

When initializing with an exact string value, it creates a predicate that checks for strict equality.

Example

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

public class Example
{
    public static void Main(string[] args)
    {
        // Create a predicate to match 'application/json' Content-Type
        var jsonPredicate = new HttpPredicateHeaderValue("Content-Type", "application/json");

        // Create a predicate with a custom logic for checking if a header value starts with 'image/'
        var imagePredicate = new HttpPredicateHeaderValue("Content-Type", value => value.StartsWith("image/", StringComparison.OrdinalIgnoreCase));

        string contentType1 = "application/json; charset=utf-8";
        string contentType2 = "image/png";
        string contentType3 = "text/plain";

        Console.WriteLine($"Is '{contentType1}' a JSON content type? {jsonPredicate.Evaluate(contentType1)}"); // Output: True
        Console.WriteLine($"Is '{contentType2}' a JSON content type? {jsonPredicate.Evaluate(contentType2)}"); // Output: False

        Console.WriteLine($"Is '{contentType1}' an image content type? {imagePredicate.Evaluate(contentType1)}"); // Output: False
        Console.WriteLine($"Is '{contentType2}' an image content type? {imagePredicate.Evaluate(contentType2)}"); // Output: True
        Console.WriteLine($"Is '{contentType3}' an image content type? {imagePredicate.Evaluate(contentType3)}"); // Output: False
    }
}
Go to Namespace