基于查询字符串参数名称的路由

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

我希望能够根据他们的名字或类型搜索产品,如下所示:

/api/products?name=WidgetX – 返回名为WidgetX /api/products?type=gadget所有产品/api/products?type=gadget – 返回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 } ); 

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

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

 config.Routes.MapHttpRoute( name: "Get Products", routeTemplate: "api/products", defaults: new { controller = "ProductSearchApi" } ); 

然后,定义两个方法,如下所示:

 GetProductsByName(string name) {} GetProductsByType(string type) {} 

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

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

您不需要在路径中包含查询参数。 应该只有一个简单的路由映射来覆盖所有ApiControllers上的Http方法:

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

您需要调整路径的唯一时间是您要将参数移动到实际路径中,而您似乎并未执行此操作。 然后你的GET http方法搜索两个字段将是:

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

如果您希望一次只显示一个字段,那么您应该考虑将不同的控制器用于不同的目的。 即,具有单个Get(string type)方法的SearchProductByTypeController 。 那么路由是/ api / SearchProductByTypeController?type = gadget

尝试更改RouteParameter.Optional string.Empty

你确定控制器没问题吗? 我的意思是,params的名字。

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