我要将一个完整的.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
}
}
这就是我在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
在请求中使用参数名称来控制路由,但事实并非如此?
是否可以重载像这样的控制器方法,其中您具有相同数量的参数,并且可以根据参数的类型或名称进行路由?
答案 0 :(得分:2)
You cannot do action overloads. The way routing works in ASP.NET Core is different than how it did in ASP.NET Web Api. However, you can simply combine these actions and then branch inside, since all params are optional:
public async Task<ActionResult<CustomerForWeb>> Get(int contactId, DateTime includeCustomersCreatedSince)
{
if (contactId != default)
{
...
}
else if (includedCustomersCreatedSince != default)
{
...
}
}