Add arbitrary route prefix to all attribute routes in webapi 2.2

Was this somehow specified in the global Api 2 route prefix for route attributes? ...

I am already using the routing attributes and the level route prefix. However, from some configuration (maybe code) I would like to add another prefix for all attribute routes. I don't want to create my own route attributes for use in my codebase, only the built-in ones.

Is it possible?

Simply put, I would like to take my routes / A / 1 / b / 2 and / X / 3 / r / 2 / r / 1 and include them (although it doesn't have to be prefixed with / api) / api / 1 / b / 2 and / api / x / 3 / g / 2 / g / 1


source to share

2 answers

Option 1

You can create an abstract base controller class that inherits all other controllers and applies an attribute to it RoutePrefix

. For example:

public abstract class BaseController : ApiController


And then my normal controllers would look like this:

public class ValuesController : BaseController
    public string GetValue()
        return "hello";


Option 2

An additional option is to use a reverse proxy , which will transparently route all incoming requests to the correct URL. You can set the proxy using a rewrite rule such as "any request that matches /api/*

, redirect to internalserver/*

". You can use ARR for IIS to do this, and it's free. I've used it in the past and it works really well for situations like this.



You can also read the Default HttpConfiguration Routes and just create a new HttpConfiguration with the only difference that you prefix routeTemplate. In the end, you are using this HttpConfiguration.

In theory, you could also create a new WebApi launcher class and the old one with HttpConfiguration as a property if you want to change routes in a separate web project.

Something like:

HttpConfiguration oldCofiguration = OtherWebService.Startup.Config;
HttpConfiguration newCofiguration = new HttpConfiguration();
foreach(var oldRoute in oldCofiguration.Routes){
            "yourPrefix" + oldRoute .routeTemplate ,
                controller = oldRoute.Controller


You need to adapt the code to your needs. (Sorry, the code is untested as I don't have access to the IDE just now)



All Articles