基于查询字符串参数名称的路由 [英] Routing based on query string parameter name

查看:32
本文介绍了基于查询字符串参数名称的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 MVC4 WebAPI 项目中配置路由.

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/products?name=WidgetX - 返回所有名为 WidgetX 的产品/api/products?type=gadget - 返回 gadget 类型的所有产品

/api/products?name=WidgetX - returns all products named WidgetX /api/products?type=gadget - returns all products of type gadget

路由配置如下:

config.Routes.MapHttpRoute(
    name: "Get by name",
    routeTemplate: "api/products/{name}",
    defaults: new { controller = "ProductSearchApi", action = "GetProductsByName", name = string.Empty }
);

config.Routes.MapHttpRoute(
    name: "Get by type",
    routeTemplate: "api/products/{type}",
    defaults: new { controller = "ProductSearchApi", action = "GetProductsByType", type = string.Empty }
);

问题是查询字符串参数的名称似乎被忽略,因此无论查询字符串参数的名称如何,总是使用第一个路由.如何修改我的路线以使其正确?

The problem is that the name of the query string parameter seems to be ignored so the first route is always the one used, regardless the name of the query string parameter. How can I modify my route to get it right?

推荐答案

你需要的只是下面的一个路由,因为查询字符串不用作路由参数:

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)
{}

路由机制智能足以根据查询字符串的名称是否与输入参数相同,将您的网址路由到您的正确操作.当然,所有带有前缀的方法都是 Get

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

您可能需要阅读以下内容:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

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

这篇关于基于查询字符串参数名称的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆