Is it possible to distinguish API routing for overloading functions?
For example I have the following functions:
[HttpGet("filter")]
public JsonResult GetCity (int id) { ... }
[HttpGet("filter")]
public JsonResult GetCity (int id, string name) { ... }
I want to call the first function if the user call it through
http://localhost:5000/api/cities/filter?id=1
and call the second using
http://localhost:5000/api/cities/filter?id=1&name=NewYork
Can we achieve it with the suggested format?
I mean with ?paramter=value
not with forward slashes like http://localhost:5000/api/cities/filter/1/NewYork
You can't have two actions like that, no. When calling an action, it only looks to see that the needed parameters are provided, and ignores any provided parameters that the action does not need.
So calling id=1&name=NewYork
will match to GetCity (int id)
because all it needs is id
, and name
gets ignored.
But then of course it matches to GetCity (int id, string name)
as well.
What you can do is keep only one action and call another method if the name
is not provided, like this:
[HttpGet("filter")]
public JsonResult GetCity(int id, string name) {
if (name == null) return GetCityWithId(id);
...
}
private JsonResult GetCityWithId(int id) {
...
}