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"); } }
To override the RoutePrefix we need to use the ~ (tilde) symbol as shown below. With the above change, now the GetTeachers() action method is mapped to URI “/tech/teachers” as expected.
The Route attribute can be applied on any controller or action method. In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config. MapHttpAttributeRoutes() method.
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.
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")]
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