路由字首

通常,控制器中的路由具有相同的字首,以某種方式與該控制器的功能連線。例如:

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) { ... }
}

在這種情況下,我們可以為整個控制器設定公共字首。為此,我們使用 [RoutePrefix] 屬性:

[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) { ... }
}

覆蓋路由字首

如果我們想要覆蓋路由字首,我們可以在方法的 routing 屬性中使用 tilde (〜)

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

    //...
}