Routing based on query string parameter name

有些话、适合烂在心里 提交于 2019-11-28 05:51:47

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

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

try changing string.Empty for RouteParameter.Optional

Are you sure that the controllers are ok? I mean, the name of the params.

    public string GetProductsByName(string name)
    {
        return "Requested name: " + name;
    }

    public string GetProductsByType(string type)
    {
        return "Requested type: " + type;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!