Note, I've read about the new routing features as part of WebApi 2.2 to allow for inheritance of routes. This does not seem to solve my particular issue, however. It seems to solve the issue of inheriting action level route attributes, but not route prefixes defined at the class level. http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-22#ARI
I would like to do something like this:
[RoutePrefix("account")]
public abstract class AccountControllerBase : ControllerBase { }
[RoutePrefix("facebook")]
public class FacebookController : AccountControllerBase
{
[Route("foo")]
public async Task<string> GetAsync() { ... }
}
[RoutePrefix("google")]
public class GoogleController : AccountControllerBase
{
[Route("bar")]
public async Task<string> GetAsync() { ... }
}
I would like the account
route prefix to be inherited, so when defining the Facebook and Google controllers, I get routes:
~/account/facebook/foo
~/account/google/bar
Currently, routes are getting defined without the account
portion from the base class.
We can override the RoutePrefix on a method, using the tilde(~) sign. We can easily define parameterized templates in the attribute based routing.
Route prefixes are associated with routes by design in attribute routing. It is used to set a common prefix for an entire controller. If you read the release notes that introduced the feature you may get a better understanding of the subject.
Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.
In the previous section, we learned that Web API can be configured in WebApiConfig class. Here, we will learn how to configure Web API routes. Web API routing is similar to ASP.NET MVC Routing. It routes an incoming HTTP request to a particular action method on a Web API controller.
I had a similar requirement. What i did was:
public class CustomDirectRouteProvider : DefaultDirectRouteProvider
{
protected override string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor)
{
var routePrefix = base.GetRoutePrefix(controllerDescriptor);
var controllerBaseType = controllerDescriptor.ControllerType.BaseType;
if (controllerBaseType == typeof(BaseController))
{
//TODO: Check for extra slashes
routePrefix = "api/{tenantid}/" + routePrefix;
}
return routePrefix;
}
}
Where BaseController
is the one defining what is the prefix. Now normal prefixes work and you can add your own. When configuring routes, call
config.MapHttpAttributeRoutes(new CustomDirectRouteProvider());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With