25

The opensource Attribute Routing allows to have multiple route-prefixes. Why does ASP.NET Web API 2.0 does not allow to have multiple RoutePrefix().

[RoutePrefix("api/v1/{abc}/Entity")]
[RoutePrefix("api/v1/{abc}/{xyz?}/Entity")]
public class MyApiController : ApiController
{
   [Route("")]
   public IHttpResult Get()
   {
      return Ok("Hello World");
   }
}
Bhalchandra K
  • 2,631
  • 3
  • 31
  • 43
  • 1
    You can add multiple RoutePrefix attribute on WebApiController. See https://3btechtalk.wordpress.com/2017/05/07/defining-multiple-route-prefix-in-asp-net-web-api-attribute-routing/ – Asad Ullah May 08 '17 at 11:18

1 Answers1

49

You can add a route to the action method also overriding the RoutePrefix with a "~"

example:

[RoutePrefix("api/v1/{abc}/Entity")]
public class MyApiController : ApiController
{
   [Route("")]
   [Route("~/api/v1/{abc}/{xyz?}/Entity")]
   public IHttpResult Get()
   {
      return Ok("Hello World");
   }
}

Notice the line: [Route("~/ api/v1/{abc}/{xyz?}/Entity")]

jaxxbo
  • 7,314
  • 4
  • 35
  • 48
  • 10
    Why is this the accepted answer? Multiple route prefixes could help avoid multiple `[Route]` attributes for each method and go a long way to helping ease maintenance on a large api controller – Dan Esparza Jun 28 '17 at 17:33