I want to let users retrieve data in three ways:
- If
isEven = null
(default) then both even and odd numbers are returned. - If
isEven = true
then even numbers are returned. - If
isEven = false
then odd numbers are returned.
[ApiController]
[Route("api/[controller]/[action]")]
public class MathematicsController : ControllerBase
{
[Route("{isEven:bool?}")]
[HttpGet]
public IActionResult GetData(bool? isEven = null)
{
var data = Enumerable.Range(1, 30).AsQueryable();
if (isEven is not null)
data = data.Where(x => (x % 2 == 0) == isEven);
return Ok(data.ToList());
}
}
Unfortunately, Swagger does not allow us to execute without selecting the dropdown box. I already set the parameter with a trailing question mark ({isEven:bool?}
) to represent that the parameter is optional. What am I missing here?
Addendum
I think Swagger UI is the culprit. I tested with Chrome by navigating to https://localhost:40443/api/mathematics/getdata
(or with a trailing slash) and it works. Case closed!
CodePudding user response:
If you have do it via path you could:
[Route("{isEven}")]
[HttpGet]
public IActionResult GetData(bool isEven) => DoGetData(isEven);
[HttpGet]
public IActionResult GetData() => DoGetData(isEven: null);
This gives you:
.../api/Mathematics/GetData/true
.../api/Mathematics/GetData/false
.../api/Mathematics/GetData