[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
这两个都返回错误:
模糊匹配异常
核心2.2,如果重要的话。
我们可以在控制器级别有一个路由,并处理字符串输入以解析为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作为可选参数怎么样?如果需要的话,您仍然可以使用seprate方法来处理实际搜索,但您有一个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
}
}
我最终只是为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