routing - 如何在 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
在请求中使用参数名称来引导路由,但情况似乎并非如此?
是否可以重载这样的控制器方法,其中您具有相同数量的参数以及基于参数类型或参数名称的路由?
解决方案
你不能做动作重载。路由在 ASP.NET Core 中的工作方式与在 ASP.NET Web Api 中的工作方式不同。但是,您可以简单地组合这些操作,然后在内部分支,因为所有参数都是可选的:
public async Task<ActionResult<CustomerForWeb>> Get(int contactId, DateTime includeCustomersCreatedSince)
{
if (contactId != default)
{
...
}
else if (includedCustomersCreatedSince != default)
{
...
}
}
推荐阅读
- python - 在 PyQt 的菜单栏下方显示图像
- php - 在数据库列中插入外键值时更新查询出现问题
- list - 从 GCP 获取所有项目所有者的列表
- python - pyqt5中自定义的可折叠qtool按钮
- c - 在C中提取具有给定概率的数字
- python - 如何在不使用任何函数的情况下从字符串中删除子字符串
- android-databinding - 将我的简单代码数据绑定一种方式转换为数据绑定两种
- sql - Elasticsearch GROUP BY 列 HAVING COUNT > x
- android-espresso - 如何为 BiometricPrompt 编写 Espresso 测试
- python - 如何从 Python 中的字符串中创建一个由包含在字符中的元素组成的列表?