Routing based on query string parameter name

前端 未结 4 520
Happy的楠姐
Happy的楠姐 2020-12-08 10:06

I\'m trying to configure routing in my MVC4 WebAPI project.

I want to be able to search for products based on their name or their type like so:

/api/pr

4条回答
  •  再見小時候
    2020-12-08 11:04

    What you need is just only one route below because query string is not used as routing parameters:

    config.Routes.MapHttpRoute(
        name: "Get Products",
        routeTemplate: "api/products",
        defaults: new { controller = "ProductSearchApi" }
    );
    

    And, then define two methods like below:

    GetProductsByName(string name)
    {}
    
    GetProductsByType(string type)
    {}
    

    Routing mechanism is smart enough to route your url to your correct action based on the name of query string whether the same with input parameters. Of course on all methods with prefix are Get

    You might need to read this: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

提交回复
热议问题