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

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

问题描述

我想在我的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 /产品名称= WidgetX - 返回名为WidgetX所有产品
<?code> / API /产品类型=小工具 - 返回式的小工具的所有产品

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

路由机制的智能的足够的路由你的URL到您的正确的动作基础上的查询字符串是否相同的输入参数的名称。当然,与preFIX所有的方法都是获取

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

您可能需要阅读:
<一href=\"http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection\">http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

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

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