Reputation: 2563
This was kind of asked at Web Api 2 global route prefix for route attributes?.
I'm using attribute routing and class level route prefixes already. However, from a configuration of some sort (could be code) I would like to add another prefix to all the attribute routes. I do not want to create custom route attributes to use throughout my code base, just the built in ones.
Is this possible?
Simply put, I would like to take my routes /a/1/b/2 and /x/3/y/2/z/1 and turn them in to (although it doesn't necessarily need to be a /api prefix) /api/1/b/2 and /api/x/3/y/2/z/1
Upvotes: 3
Views: 3405
Reputation: 3476
You could also read the Routes of the default HttpConfiguration and just create a new HttpConfiguration with the only difference that you apply a prefix to the routeTemplate. At the end you use this HttpConfiguration then.
Theoretically you could also create a new WebApi Startup class and your old one provides it's HttpConfiguration as a property in case you want to change routes in a seperate web project.
Something like:
HttpConfiguration oldCofiguration = OtherWebService.Startup.Config;
HttpConfiguration newCofiguration = new HttpConfiguration();
foreach(var oldRoute in oldCofiguration.Routes){
newCofigurationRoutes.MapHttpRoute(
"YourRouteName",
"yourPrefix" + oldRoute .routeTemplate ,
new
{
controller = oldRoute.Controller
},
null,
null
);
}
You need to adapt the code to your needs. (Sorry the code is untested, as I have no access to IDE just now)
Upvotes: 0
Reputation: 118947
Option 1
You could create an abstract base controller class that all other controllers inherit from and apply the RoutePrefix
attribute to that. For example:
[RoutePrefix("/api")
public abstract class BaseController : ApiController
{
}
And then my normal controllers would look like this:
public class ValuesController : BaseController
{
[Route("/get/value")]
public string GetValue()
{
return "hello";
}
}
Option 2
A secondary option is to use a reverse proxy that will transparently route all incoming requests to the correct URL. You could set the proxy up with a rewrite rule such as "any request that matches /api/*
, redirect to internalserver/*
". You can use ARR for IIS to do this and it is free. I have used it in the past and it works very well for situations like this.
Upvotes: 2