Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 - returns all products named WidgetX /api/products?type=gadget - returns all products of type gadget

The routes are configured like this:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
146 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...