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

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

我正在将完整的.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在请求中使用参数名称来引导路由,但似乎并非如此?

有没有可能重载这样的控制器方法,你有相同数量的参数,并根据参数的类型或参数的名称路由?

routing asp.net-core-webapi asp.net-web-api-routing asp.net-core-2.2
1个回答
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)
    {
        ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.