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
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