如何区分基于ASP.NET核心属性的重载函数路由

问题描述 投票:2回答:1

是否可以区分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这样的正斜线

c# asp.net-core asp.net-web-api-routing asp.net-core-routing
1个回答
4
投票

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

所以调用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) {
        ...
    }
© www.soinside.com 2019 - 2024. All rights reserved.