Routing based on query string parameter name

前端 未结 4 518
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:10

    You don't need to include your query parameters in the route. There should only be one simple route map to cover the Http Methods on all of your ApiControllers:

    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    

    The only time you need to adjust the routes is if you want to move a parameter into the actual path, which you don't seem to be doing. Then your GET http method to search by two fields would be:

    public IEnumerable Get(string name, string type){
        //..your code will have to deal with nulls of each parameter
    }
    

    If you want to explicitly search by one field at a time then you should think about using different controllers for different purposes. Ie, a SearchProductByTypeController that has a single Get(string type) method. The route would then be /api/SearchProductByTypeController?type=gadget

提交回复
热议问题