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.
Asked
Active
Viewed 1,112 times
2 Answers
4
The ApiVersionAttribute intentionally is not inherited because if you use inheritance on your controllers, for example V2.Controllers.ValuesController
inherits from V1.Controllers.ValuesController
, you end up with two controllers with the same route that both implement 1.0, which is ambiguous and will produce an error.
There are several possible ways to achieve your goal:
- Create your own attribute, extending ApiVersionsBaseAttribute, allow it to be inherited and apply it to a base class.
- Create your own attribute, implement IApiVersionProvider, allow it to be inherited, and apply it to a base class.
- Enumerate all controller types in your configuration setup and use a convention that applies one or more API versions to all controllers.
options.Conventions.Controller(controllerType).HasApiVersion(1.0);
. This will be unioned with an explicit attributes (ex: 1.1) - You can author a custom convention, which applies one or more API versions to all or specific controllers. Currently, the convention can only be applied to an entire controller, but per-action support will be available in the next major release (as there are breaking changes to the API, even though there is no visible change for most). For example,
options.Conventions.Add(new MyConvention(new ApiVersion(1,0)));
.
I hope that helps.

Chris Martinez
- 3,185
- 12
- 28
3
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.

Manoj Choudhari
- 5,277
- 2
- 26
- 37
-
Thanks, this looks just like my current setup. However I have a situation where some controls might be on version 1.1 and some still on version 1.0. And client will still send version 1.1 . The solution I found so far is to decorate all controls with both versions but that seems semi optimal. Was hoping I can just set all attributes on base class, but I don't think this will work – Vitalii Kalinin Mar 20 '19 at 21:32