asp.net-web-api2 Route prefixes


Example

Usually, the routes in a controller have the same prefix connected somehow with functionality of this controller. For example:

public class ProductsController : ApiController
{
    [Route("api/products")]
    public IEnumerable<Product> GetProducts() { ... }

    [Route("api/products/{id:int}")]
    public Product GetProduct(int id) { ... }

    [Route("api/products")]
    [HttpPost]
    public HttpResponseMessage CreateProduct(Product product) { ... }
}

In such scenario we can set common prefix for whole controller. To do so we use the [RoutePrefix] attribute:

[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
    // GET api/products
    [Route("")]
    public IEnumerable<Product> GetProducts() { ... }

    // GET api/products/5
    [Route("{id:int}")]
    public Product GetProduct(int id) { ... }

    //POST api/products
    [Route("")]
    [HttpPost]
    public HttpResponseMessage CreateProduct(Product product) { ... }
}

Overriding route prefix

If we want to override the route prefix we can use a tilde (~) in the routing attribute of the method:

[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
    // GET api/owners/products
    [Route("~/api/owners/products")]
    public IEnumerable<Product> GetProducts() { ... }

    //...
}