Table of Contents

Class VaryAcceptMiddleware

Namespace
Cuemon.AspNetCore.Http.Headers
Assembly
Cuemon.AspNetCore.dll

Middleware that appends Vary: Accept to every response, signalling to HTTP caches (and clients) that the representation varies based on the Accept request header (RFC 9110 ยง12.5.5).

public class VaryAcceptMiddleware : Middleware
Inheritance
VaryAcceptMiddleware
Inherited Members

Examples

The following example demonstrates how to register the to append a Vary: Accept header to every response.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;

        namespace Cuemon.AspNetCore.Http.Headers;

        public static class VaryAcceptMiddlewareExample
        {
            public static async Task DemonstrateAsync()
            {
                var context = new DefaultHttpContext();
        var middleware = new VaryAcceptMiddleware(httpContext => httpContext.Response.WriteAsync("Hello"));

        await middleware.InvokeAsync(context);
        Console.WriteLine(context.Response.Headers[HeaderNames.Vary].ToString());
            }
        }

Constructors

VaryAcceptMiddleware(RequestDelegate)

Initializes a new instance of the VaryAcceptMiddleware class.

public VaryAcceptMiddleware(RequestDelegate next)

Parameters

next RequestDelegate

The next RequestDelegate in the ASP.NET Core request processing pipeline. This delegate is invoked after this middleware has performed its work.

Methods

InvokeAsync(HttpContext)

Invokes the middleware for the given HttpContext. Adds the Vary: Accept response header just before the response starts.

public override Task InvokeAsync(HttpContext context)

Parameters

context HttpContext

The current HttpContext.

Returns

Task

A Task that represents the asynchronous operation of this middleware. The returned task completes when the remaining pipeline has finished processing.

Remarks

The header is appended using OnStarting(Func<Task>) to ensure the header is present even if the response body is being streamed or the response was started by downstream middleware. This signals to intermediaries and clients that the response representation depends on the request's Accept header.