Search code examples
c#.netasp.net-web-api2api-versioning

Specify API version for all WEB API controllers


I am building an API using Web API .NET 2, created a BaseController class which all other controllers inherit. I would like to apply API versioning using [ApiVersion()] attribute, however I don't want to decorate each controller class with same attributes if I have more than one version of API. Is there a way to set all possible API versions for all controllers? I tried to set attributes on BaseController class, but unfortunately attributes are not inherited by derived classes.


Solution

  • You can use ApiVersioning middleware as shown in below example

    services.AddApiVersioning(
        o =>
        {
            o.AssumeDefaultVersionWhenUnspecified = true );
            o.DefaultApiVersion = new ApiVersion( 1,0);
        } );
    

    It sets default version for all controllers to be 1.0. Also if version is not specified, the call will be routed to controller with default version.

    If you want to create new version of existing controller, then you can specify the version attribute on that controller.

    Hope this helps.