c# - 如何区分ASP.NET Core基于属性的路由重载函数

标签 c# asp.net-core asp.net-web-api-routing asp.net-core-routing

是否可以区分重载函数的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/

相关文章:

c# - 反序列化 Json 以列出 C#

c# - 我如何伪造 Assembly.LoadFile 和 Assembly.GetTypes?

c# - System.Diagnostic.Debug.WriteLine 在 ASP.NET 5 Web API 中不起作用

asp.net - WS-Federation 登录 Asp.NET 5 MVC 6 ADFS

asp.net - ASP.NET Core WebAPI 中的 AAD V2 与 JwtBearer

asp.net-mvc-4 - 具有不同参数名称的 Web api 路由方法

c# - 名为 'DefaultApi' 的路由已经在路由集合中

c# - 如何在 Windows 安装程序的自定义操作中获取当前用户名?

c# - C#中的双字节字符串比较

c# - 如何修复 webAPI 中不正确的操作路由