Table of Contents

Class HeaderDictionaryExtensions

Namespace
Cuemon.Extensions.AspNetCore.Http
Assembly
Cuemon.Extensions.AspNetCore.dll

Extension methods for the IHeaderDictionary interface.

public static class HeaderDictionaryExtensions
Inheritance
HeaderDictionaryExtensions

Examples

The following example demonstrates how to add or update HTTP headers in an IHeaderDictionary using the HeaderDictionaryExtensions class.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Cuemon.Extensions.AspNetCore.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;

namespace MyApp.Examples;

public class HeaderDictionaryExtensionsExample
{
    public void Demonstrate()
    {
        var headers = new HeaderDictionary();

        // Add or update a single header
        headers.AddOrUpdateHeader("X-Custom", new StringValues("my-value"));

        // Add or update multiple headers from an HttpResponseHeaders collection
        var responseMessage = new HttpResponseMessage();
        responseMessage.Headers.Add("X-Trace", "abc123");
        responseMessage.Headers.Add("X-Session", "session-456");

        headers.AddOrUpdateHeaders(responseMessage.Headers);

        // Verify headers
        Console.WriteLine(headers["X-Custom"]);      // my-value
        Console.WriteLine(headers["X-Trace"]);       // abc123
        Console.WriteLine(headers["X-Session"]);     // session-456

}
}

Methods

AddOrUpdateHeader(IHeaderDictionary, string, StringValues, bool)

Attempts to add or update an existing element with the provided key and value to the IHeaderDictionary.

public static void AddOrUpdateHeader(this IHeaderDictionary dictionary, string key, StringValues value, bool useAsciiEncodingConversion = true)

Parameters

dictionary IHeaderDictionary

The IHeaderDictionary to extend.

key string

The string to use as the key of the element to add.

value StringValues

The string to use as the value of the element to add.

useAsciiEncodingConversion bool

if set to true an ASCII encoding conversion is applied to the value.

AddOrUpdateHeaders(IHeaderDictionary, HttpResponseHeaders)

Attempts to add or update one or more elements from the provided collection of responseHeaders to the IHeaderDictionary.

public static void AddOrUpdateHeaders(this IHeaderDictionary dictionary, HttpResponseHeaders responseHeaders)

Parameters

dictionary IHeaderDictionary

The IHeaderDictionary to extend.

responseHeaders HttpResponseHeaders

The HttpResponseHeaders to copy.