Table of Contents

RestfulApiVersionReader Class

Definition

Namespace
Codebelt.Extensions.Asp.Versioning
Assemblies
Codebelt.Extensions.Asp.Versioning.dll
Source
src/Codebelt.Extensions.Asp.Versioning/RestfulApiVersionReader.cs

Represents a RESTful API version reader that reads the value from a filtered list of Accept headers in the request.

public class RestfulApiVersionReader : MediaTypeApiVersionReader, IApiVersionReader, IApiVersionParameterSource
Inheritance
MediaTypeApiVersionReader
RestfulApiVersionReader
Implements
IApiVersionReader
IApiVersionParameterSource
Inherited Members
MediaTypeApiVersionReader.AddParameters(IApiVersionParameterDescriptionContext)
MediaTypeApiVersionReader.ParameterName

Examples

Use RestfulApiVersionReader when you need fine-grained control over which Accept media types are eligible for version parsing — for example when configuring AddApiVersioning directly rather than using the AddRestfulApiVersioning convenience method. The reader filters the incoming Accept header collection to only the entries whose media types start with one of the configured validAcceptHeaders values before delegating to MediaTypeApiVersionReader, which prevents browser-injected entries such as text/html or image/webp from being misread as version indicators.

using System.Collections.Generic;
using Asp.Versioning;
using Codebelt.Extensions.Asp.Versioning;
using Microsoft.Extensions.DependencyInjection;

namespace Codebelt.Extensions.Asp.Versioning;

public class CustomVersioningSetup
{
    public static void ConfigureServices(IServiceCollection services)
    {
        var acceptHeaders = new List<string>
        {
            "application/json",
            "application/xml",
            "text/json",
            "text/xml",
            "text/plain",
            "*/*"
        };

        services.AddApiVersioning(o =>
        {
            o.DefaultApiVersion = new ApiVersion(1, 0);
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.ApiVersionReader = new RestfulApiVersionReader(acceptHeaders, "v");
        });
    }
}

Remarks

This class was introduced to have an inclusive filter on what MIME types to consider valid when parsing HTTP Accept headers; for more information have a read at https://github.com/dotnet/aspnet-api-versioning/issues/887

Constructors

Name Description
RestfulApiVersionReader(IEnumerable<string>, string)

Initializes a new instance of the RestfulApiVersionReader class.

Properties

Name Description
ValidAcceptHeaders

Gets the valid accept headers that ReadAcceptHeader(ICollection<MediaTypeHeaderValue>) will filter by.

Methods

Name Description
Read(HttpRequest)

Reads the requested API version from the HTTP request.

ReadAcceptHeader(ICollection<MediaTypeHeaderValue>)

Reads the requested API version from the HTTP Accept header.