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
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.

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.


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.


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.


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