Search code examples
asp.net-mvcasp.net-web-apiasp.net-web-api-routing

Web Api 2 global route prefix for route attributes?


I'd like to expose a company's api by two ways:

  • api.company.com (pure WebApi web site)

  • company.com/api (add WebApi to existing MVC5 company site)

So, I placed models/controllers in a separate assembly and reference it from both web sites.

Also, I use route attributes:

[RoutePrefix("products")]
public class ProductsController : ApiController

Now, the controller above can be accessed by:

  • api.company.com/products which is good

  • company.com/products which I'd like to change to company.com/api/products

Is there a way to keep using route attributes and setup MVC project so it adds "api" for all routes?


Solution

  • So this is probably not the only way you could do it, but this is how I would do it:

    1. Create your own Attribute that inherits from RoutePrefixAttribute
    2. Override the Prefix property and add some logic in there to prepend "api" to the prefix if running on the desired server.
    3. Based on a setting in your web.config, prepend to the route or not.

      public class CustomRoutePrefixAttribute : RoutePrefixAttribute
      {
      
        public CustomRoutePrefixAttribute(string prefix) : base(prefix)
        {
        }
      
        public override string Prefix
        {
          get
          {
              if (Configuration.PrependApi)
              {
                  return "api/" + base.Prefix;
              }
      
              return base.Prefix;
          }
        }
      }
      

    EDIT (The below option is no longer supported as of Web API 2.2)

    Alternatively you could also specify more than one route prefix:

    [RoutePrefix("api/products")]
    [RoutePrefix("products")]
    public class ProductsController : ApiController