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

Routing 如何在ASP.NET核心Web API中重载具有相同数量参数的控制器方法?,routing,asp.net-core-webapi,asp.net-web-api-routing,asp.net-core-2.2,Routing,Asp.net Core Webapi,Asp.net Web Api Routing,Asp.net Core 2.2,我正在将一个完整的.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

我正在将一个完整的.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错误,取而代之的是这个错误:

“{\”错误\:\”请求匹配了多个端点。匹配:\r\n\r\n[AssemblyName].Controllers.CustomerController.Get([AssemblyName])\r\n[AssemblyName].Controllers.CustomerController.Get([AssemblyName])\”}”

这是我的完整.NET framework应用程序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
    }
}
[RequireHttps]
公共类CustomerController:ApiController
{
[HttpGet]
[响应类型(类型(CustomerForWeb))]
公共异步任务Get(int contactId)
{
//一些代码
}
[HttpGet]
[响应类型(类型(列表))]
公共异步任务Get(日期时间includeCustomersCreatedSince)
{
//其他代码
}
}
这就是我在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
    }
}
[产生(“应用程序/json”)]
[RequireHttps]
[路由(“api/[控制器]”)]
[ApiController]
公共类CustomerController:控制器
{
public async任务在请求中使用参数名来引导路由,但情况似乎并非如此


如果您有相同数量的参数,并且路由基于参数的类型或名称,那么是否可以重载这样的控制器方法?

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

public async Task<ActionResult<CustomerForWeb>> Get(int contactId, DateTime includeCustomersCreatedSince)
{
    if (contactId != default)
    {
        ...
    }
    else if (includedCustomersCreatedSince != default)
    {
        ...
    }
}
public async Task Get(int contactId,DateTime includeCustomersCreatedSince)
{
如果(contactId!=默认值)
{
...
}
else if(包括CustomerCreatedSince!=默认值)
{
...
}
}

Ah这就解释了!如果有两个相同类型的参数,例如
Get(int companyId,int personId),会发生什么情况
如果您只想使用personId,是否需要调用
Customer/Get?personId=1234
?即,路由是否使用参数的类型或参数名称进行匹配?是的。它将通过名称绑定。我不明白为什么他们不可能为不同的参数重载方法…制作一个
If/else if/else if/…/else
在处理可以组合在一起或不能组合在一起的查询字符串参数时非常令人不快。。。