具有单个参数的多个GET()方法导致AmbiguousMatchException:请求与多个端点匹配

[HttpGet]
public actionResult<IEnumerable<string>> Get()
{
}

[HttpGet("{id}")]
public actionResult<string> Get([FromRoute]int id)
{
}

[HttpGet]
public actionResult<IEnumerable<string>> Get()([FromQuery]DateTime dateTime)
{
}

我可以达到第二:

https://localhost:44341/api/Orders/3

但是对于第一个和第三个:

https://localhost:44341/api/Orders
https://localhost:44341/api/Orders?dateTime=2019-11-01T00:00:00

这两个都返回错误:

  

AmbiguousMatchException

Core 2.2,如果有关系的话。

hotdog33 回答:具有单个参数的多个GET()方法导致AmbiguousMatchException:请求与多个端点匹配

我最终只是为GetByDate方法创建了一个不同的端点。


[HttpGet]
public ActionResult<string> Get()
{
    //
}


[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
    //
}


[HttpGet("ByDate/{date}")]
public ActionResult<string> ByDate(DateTime date)
{
    //
}

它们可以称为:

https://localhost:44341/api/controller
https://localhost:44341/api/controller/1
https://localhost:44341/api/controller/getbydate/2019-11-01
,

我们可以在控制器级别设置一条路由,并处理如下输入的字符串以解析为int或date

 [Route("api/[controller]/{id}")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values/5
        [HttpGet()]
        public ActionResult<string> Get(string id)
        {

            if (int.TryParse(id,out int result))
            {
                return Ok(id);

            }
            else if (DateTime.TryParse(id,out DateTime result1))
            {
                return Ok(id);
            }
            else
                return Ok("Failed");
        }
    }
,

将Id和date作为可选参数如何?如果需要,您仍然可以使用单独的方法来处理实际搜索,但是只有一个GET方法。

    [HttpGet("{id}")]
    public IActionResult Get([FromRoute]int? id [FromQuery]DateTime? dateTime)
    {
      if(id.HasValue)
      {
        //Do Something with the id
      } 
      else if (dateTime.HasValue)
      {
        //Do Something with the date
      }
    else 
    {
     //return all
    }
 }
本文链接:https://www.f2er.com/3147158.html

大家都在问