Search code examples
asp.net-web-api2aspnet-api-versioning

Can AddApiVersioning() be used without attributing every controller?


I'm versioning my Asp.Net Web Api 2 api using config.AddApiVersioning() in my WebApiConfig. Each of my controllers is decorated with something like [Route("api/TestApi/v{version:apiVersion}/{action}/{id?}")].

I would like to remove most of those decorations and instead use something like this in my WebApiConfig:

config.Routes.MapHttpRoute(
    "ApiControllerVersionActionId",
    "api/{controller}/v{version:apiVersion}/{action}/{id}",
    new { id = UrlParameter.Optional },
    new
    {
        // e.g., 1.0, 12.75
        apiVersion = @"^[0-9]+\.[0-9]+$",

        // only GUIDs or integers
        id = @"^(\{){0,1}(\(){0,1}[0-9a-fA-F]{8}\-{0,1}[0-9a-fA-F]{4}\-{0,1}[0-9a-fA-F]{4}\-{0,1}[0-9a-fA-F]{4}\-{0,1}[0-9a-fA-F]{12}(\)){0,1}(\}){0,1}$|^\d+$"
    }
);

My questions:

  • Is this possible?
  • Are there examples? Most examples I've found decorate all the controllers.

Solution

  • I have solved this issue and am now able to remove all the RouteAttributes from my controllers.

    The issue was with the constraints. I've modified my MapHttpRoute to be the following:

    config.Routes.MapHttpRoute(
        "ApiControllerVersionActionId",
        "api/{controller}/v{apiVersion}/{action}/{id}",
        new { id = UrlParameter.Optional },
        new
        {
            apiVersion = new ApiVersionRouteConstraint(),
    
            // empty string, guid, or int
            id = @"^$|^(\{){0,1}(\(){0,1}[0-9a-fA-F]{8}\-{0,1}[0-9a-fA-F]{4}\-{0,1}[0-9a-fA-F]{4}\-{0,1}[0-9a-fA-F]{4}\-{0,1}[0-9a-fA-F]{12}(\)){0,1}(\}){0,1}$|^\d+$"
        }
    );