Search code examples
asp.net-web-api2attributerouting

Get the route value from url in webapi attribute routing


I have a webAPI controller which is like

Public class TestController:APIController
{ 


   [Route(“Api/Test/{testId}/SubTest”)] 
     Public  void Post(int subTestid)
     {
     }

}

Our requirement is to get the value of testId from the url inside the post method. Could anyone suggest the best way to achieve this.


Solution

  • Looking at this link: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

    The string "customers/{customerId}/orders" is the URI template for the route. Web API tries to match the request URI to the template. In this example, "customers" and "orders" are literal segments, and "{customerId}" is a variable parameter.

    public class OrdersController : ApiController
    {
        [Route("customers/{customerId}/orders")]
        [HttpGet]
        public IEnumerable<Order> FindOrdersByCustomer(int customerId) { ... }
    }
    

    It seems that you need to change subTestid to testId so it will be a match.