Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API multiple RoutePrefix

Tags:

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");    } } 
like image 363
Bhalchandra K Avatar asked Jul 25 '14 10:07

Bhalchandra K


People also ask

How do you override the prefix route?

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.

How to use route attribute in web API?

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.

Which routing support in asp net web API 2?

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.


1 Answers

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")]

like image 156
jaxxbo Avatar answered Oct 25 '22 02:10

jaxxbo