【问题标题】:How to distinguish ASP.NET Core Attribute-based Routing for Overloading Functions如何区分重载函数的 ASP.NET Core 基于属性的路由
【发布时间】:2017-12-22 14:20:15
【问题描述】:

是否可以区分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 方法不支持重载。

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


【解决方案1】:

你不能有两个这样的动作,不。调用动作时,它只查看是否提供了所需的参数,并忽略任何提供的动作不需要的参数。

所以调用id=1&name=NewYork 将匹配GetCity (int id),因为它只需要id,而name 会被忽略。

当然它也匹配GetCity (int id, string name)

如果没有提供name,您可以只保留一个操作并调用另一个方法,如下所示:

    [HttpGet("filter")]
    public JsonResult GetCity(int id, string name) {
        if (name == null) return GetCityWithId(id);
        ...
    }

    private JsonResult GetCityWithId(int id) {
        ...
    }

【讨论】:

    猜你喜欢
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多