Table of Contents

VaryAcceptMiddleware Class

Definition

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 invoke against a DefaultHttpContext and observe the Vary: Accept header written when the response starts.

// Program.cs
using System;
using System.Threading.Tasks;
using Cuemon.AspNetCore.Http.Headers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Net.Http.Headers;

var responseFeature = new CapturingHttpResponseFeature();
var context = new DefaultHttpContext();
context.Features.Set<IHttpResponseFeature>(responseFeature);

var middleware = new VaryAcceptMiddleware(async httpContext =>
{
    await responseFeature.FireOnStartingAsync();
    await httpContext.Response.WriteAsync("Hello");
});

await middleware.InvokeAsync(context);

Console.WriteLine($"{HeaderNames.Vary}: {context.Response.Headers[HeaderNames.Vary]}");

sealed class CapturingHttpResponseFeature : HttpResponseFeature
{
    private Func<Task>? _onStarting;

    public override void OnStarting(Func<object, Task> callback, object state)
    {
        var prior = _onStarting;
        _onStarting = async () =>
        {
            await callback(state);
            if (prior != null) { await prior(); }
        };
    }

    public Task FireOnStartingAsync() => _onStarting?.Invoke() ?? Task.CompletedTask;
}

Constructors

Name Description
VaryAcceptMiddleware(RequestDelegate)

Initializes a new instance of the VaryAcceptMiddleware class.

Methods

Name Description
InvokeAsync(HttpContext)

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