如何在路由解析中包括查询字符串,以允许具有相同方法,路由和查询字符串的多个操作? [英] How to include Query String in the route resolution in order to allow multiple Actions with the same Method, Route and Query String?
问题描述
我正在将ASP.NET MVC(.NET Framework)应用程序转换为ASP.NET Core MVC.严格来说,这是一次转换,我无法进行任何重大更改,因此无法更改任何路径或方法.我无法匹配ASP.NET Core MVC中的相同功能.
I am converting an ASP.NET MVC (.NET Framework) application to ASP.NET Core MVC. This is strictly a conversion, I cannot make any breaking changes hence I cannot change any Routes or Methods. I am unable to match the same functionality in ASP.NET Core MVC.
有效的ASP.NET MVC:
Working ASP.NET MVC:
[HttpPut]
[Route("status")]
public async Task<IHttpActionResult> UpdateStatusByOrderGuid([FromUri] Guid orderGUID, [FromBody] POST_Status linkStatusModel)
{
}
[HttpPut]
[Route("status")]
public async Task<IHttpActionResult> UpdateStatusById([FromUri] Guid id, [FromBody] POST_Status linkStatusModel)
{
}
ASP.NET Core MVC无法正常工作.
Not working, ASP.NET Core MVC.
我收到一个错误:
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException:该请求匹配了多个端点
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints
代码:
[HttpPut]
[Route("status")]
public async Task<IActionResult> UpdateStatusByOrderGuid([FromQuery] Guid orderGUID, [FromBody] POST_Status statusModel)
{
}
[HttpPut]
[Route("status")]
public async Task<IActionResult> UpdateStatusById([FromQuery] Guid id, [FromBody] POST_Status statusModel)
{
}
在解析哪个路由时,我需要包括查询参数.它应根据查询字符串中是orderGUID
还是id
进行匹配.
I need to include the query parameters when it resolves which route. It should match based on whether orderGUID
or id
is in the query string.
谢谢.
推荐答案
为什么不使用单个端点?您不需要传递Guid,因为它是GET操作,因此您可以传递字符串并在以后进行转换.这样,您可以发送一个参数或另一个参数.
Why not use a single endpoint instead? You don't need to pass Guid's, since it's a GET operation, you can pass strings and cast them later. That way you can send one parameter or the other.
[HttpPut]
[Route("status")]
public async Task<IActionResult> UpdateStatus([FromBody] POST_Status statusModel, [FromQuery] string orderGUID = null, [FromQuery] string id = null)
{
if (!string.IsNullOrEmpty(orderGUID))
{
// UpdateStatusByOrderGuid implementation here
// Guid guid = Guid.Parse(orderGUID);
}
else if (!string.IsNullOrEmpty(id))
{
// UpdateStatusById implementation here
// Guid guid = Guid.Parse(id);
}
else
{
throw new ArgumentException("No valid GUID.");
}
}
此端点应与您指定的两种方案兼容.
This endpoint should be compatible with both scenarios you specified.
这篇关于如何在路由解析中包括查询字符串,以允许具有相同方法,路由和查询字符串的多个操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!