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

ric*_*fox 25 c# query-string asp.net-web-api asp.net-web-api-routing

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

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

/api/products?name=WidgetX- 返回名为WidgetX的所有产品 /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 }
);
Run Code Online (Sandbox Code Playgroud)

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

cuo*_*gle 30

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

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

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

GetProductsByName(string name)
{}

GetProductsByType(string type)
{}
Run Code Online (Sandbox Code Playgroud)

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

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


Nic*_*ick 5

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

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

唯一需要调整路由的时间是如果您想将参数移动到实际路径中,而您似乎没有这样做。那么您GET按两个字段搜索的 http 方法将是:

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

如果您想一次按一个字段进行显式搜索,那么您应该考虑将不同的控制器用于不同的目的。即,SearchProductByTypeController具有单一Get(string type)方法的 a 。然后路由将是 /api/SearchProductByTypeController?type=gadget