Iman Memarpour Iman Memarpour -4 years ago 110
C# Question

When to use Route data and when to use query string in ASP.NET Web API?

While passing parameters to web API controllers, Is there any rule on whether to use Route data like
http://domain/api/employees/1
or to use query string like
http://domain/api/employees?id=1
Is it totally option based or Is there any guideline on this? does one has any advantage over the other one?
I found many questions on how to implement Route data or query string, but I don't know which one should I use when both would do the job.

Answer Source

Query strings are nice if you have many parameters that are optional. Unlike the default behavior or routing, this is useful if you have parameters that can exist without any preceding parameters. An example of this might be a search feature with many fields.

/q=test%20query&city=some%20city&state=some%20state&occupation=programmer
/q=foo%20bar&occupation=dancer&state=CA

Unlike the default behavior of routing, query string parameters can be supplied in any order and in any combination.

Routing makes for more SEO-friendly URLs. But with the built-in routing, "optional" parameters mean only that the right-most parameter is optional.

/search/foo%20bar/CA/dancer
/search/foo%20bar/CA
/search/foo%20bar

So, you wouldn't be able to do:

/search/foo%20bar/dancer

because it would put the value "dancer" into the route value with the "state" route key.

You can extend routing to make optional parameters that can be supplied in any order, but it is more involved to set up.

/search/query/occupation/dancer/foo%20bar/state/CA/
/search/state/CA/query/foo%20bar
/search/query/foo%20bar/occupation/dancer

Do note that there is one major difference between the two. Query string parameters are not handled by routing (by default, anyway). The reason why they make it to the action method is because they are supplied by value providers. You can control whether query string or route values take precedence (for the entire application) by changing the order of value provider factories.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download