2012-09-27 74 views
24

我试图在我的MVC4 WebAPI项目中配置路由。基于查询字符串参数名称的路由

我希望能够基于他们的名字或他们的类型,像这样以搜索产品:

/api/products?name=WidgetX - 返回名为WidgetX /api/products?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 } 
); 

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

回答

30

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

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

0

尝试改变string.EmptyRouteParameter.Optional

+0

RouteParameter会让我使用像/产品/ ABC这当然会不符合要求的URL。我需要能够使用查询字符串参数。 – rickythefox

4

你并不需要在路线查询参数。应该只有一个简单的路线图,以覆盖所有的ApiControllers的HTTP方法:

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

你需要调整路线的唯一情况是,如果你想一个参数进入实际的路径,你似乎没有这样做。如果你想在同一时间通过一个字段来精确搜索,那么你应该考虑使用不同的控制器用于不同的目的

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

:那么你GET HTTP方法由两个字段进行搜索会。即,具有单个Get(string type)方法的SearchProductByTypeController。然后路由将是/ api/SearchProductByTypeController?type = gadget

+0

谢谢,有时候这个问题不在代码中,而是在架构中。 ;) – rickythefox

+1

什么样的资源是'SearchProductByTypeController'? :P –

0

您确定控制器正常吗?我的意思是,参数的名称。

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

    public string GetProductsByType(string type) 
    { 
     return "Requested type: " + type; 
    } 
相关问题