tom*_*dox 4 routing asp.net-web-api-routing asp.net-core-webapi asp.net-core-2.2
我正在将一个完整的 .NET Framework Web API 2 REST 项目迁移到 ASP.NET Core 2.2 并且在路由中有点迷失。
在网络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
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我在 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
}
}
Run Code Online (Sandbox Code Playgroud)
如果我注释掉一种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)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4065 次 |
| 最近记录: |