While passing parameters to web API controllers, Is there any rule on whether to use Route data like
or to use query string like
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.
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.
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:
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.