是否可以区分重载函数的API路由?
例如我有以下功能:
[HttpGet("filter")]
public JsonResult GetCity (int id) { ... }
[HttpGet("filter")]
public JsonResult GetCity (int id, string name) { ... }
如果用户通过调用第一个函数,我想调用它
http://localhost:5000/api/cities/filter?id=1
并使用
调用第二个http://localhost:5000/api/cities/filter?id=1&name=NewYork
我们可以用建议的格式实现它吗?
我的意思是使用 ?paramter=value
而不是像 http://localhost:5000/api/cities/filter/1/NewYork
最佳答案
你不能有这样的两个 Action ,不。当调用一个 Action 时,它只查看是否提供了所需的参数,并忽略任何提供的该 Action 不需要的参数。
因此调用 id=1&name=NewYork
将匹配 GetCity (int id)
因为它所需要的只是 id
和 name
被忽略。
当然它也与 GetCity (int id, string name)
匹配。
如果未提供名称
,您可以只保留一个操作并调用另一个方法,如下所示:
[HttpGet("filter")]
public JsonResult GetCity(int id, string name) {
if (name == null) return GetCityWithId(id);
...
}
private JsonResult GetCityWithId(int id) {
...
}
关于c# - 如何区分ASP.NET Core基于属性的路由重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47943012/