首页 > 解决方案 > 如何在 ASP.NET Core Web API 中重载具有相同数量参数的控制器方法?

问题描述

我正在将一个完整的 .NET Framework Web API 2 REST 项目迁移到 ASP.NET Core 2.2 并且在路由中有点迷失。

在 Web API 2 中,我能够根据参数类型使用相同数量的参数重载路由,例如,我可以拥有Customer.Get(int ContactId)并且Customer.Get(DateTime includeCustomersCreatedSince)传入的请求将被相应地路由。

我无法在 .NET Core 中实现相同的目标,我要么收到 405 错误,要么收到 404,而是出现此错误:

"{\"error\":\"请求匹配多个端点。匹配项:\r\n\r\n[AssemblyName].Controllers.CustomerController.Get ([AssemblyName])\r\n[AssemblyName].Controllers.CustomerController.Get ([AssemblyName])\"}"

这是我的完整 .NET 框架应用程序 Web API 2 应用程序中的工作代码:

[RequireHttps]    
public class CustomerController : ApiController
{
    [HttpGet]
    [ResponseType(typeof(CustomerForWeb))]
    public async Task<IHttpActionResult> Get(int contactId)
    {
       // some code
    }

    [HttpGet]
    [ResponseType(typeof(List<CustomerForWeb>))]
    public async Task<IHttpActionResult> Get(DateTime includeCustomersCreatedSince)
    {
        // some other code
    }
}

这就是我在 Core 2.2 中将其转换为的内容:

[Produces("application/json")]
[RequireHttps]
[Route("api/[controller]")]
[ApiController]
public class CustomerController : Controller
{
    public async Task<ActionResult<CustomerForWeb>> Get([FromQuery] int contactId)
    {
        // some code
    }

    public async Task<ActionResult<List<CustomerForWeb>>> Get([FromQuery] DateTime includeCustomersCreatedSince)
    {
        // some code
    }
}

如果我注释掉其中一种Get方法,上面的代码就可以工作,但是一旦我有两种Get方法就会失败。我希望FromQuery在请求中使用参数名称来引导路由,但情况似乎并非如此?

是否可以重载这样的控制器方法,其中您具有相同数量的参数以及基于参数类型或参数名称的路由?

标签: routingasp.net-core-webapiasp.net-web-api-routingasp.net-core-2.2

解决方案


你不能做动作重载。路由在 ASP.NET Core 中的工作方式与在 ASP.NET Web Api 中的工作方式不同。但是,您可以简单地组合这些操作,然后在内部分支,因为所有参数都是可选的:

public async Task<ActionResult<CustomerForWeb>> Get(int contactId, DateTime includeCustomersCreatedSince)
{
    if (contactId != default)
    {
        ...
    }
    else if (includedCustomersCreatedSince != default)
    {
        ...
    }
}

推荐阅读