问题出现的原因是Swagger并不支持GET请求中的可选参数。但是可以使用另一种方式来实现同样的功能,即在GET请求中使用查询字符串来传递参数。
以下是一个示例代码,其中我们将应用程序的“WeatherForecast”控制器中的GET请求的可选参数转换为查询字符串:
[HttpGet]
public IEnumerable Get([FromQuery] string startDate = null, [FromQuery] string endDate = null)
{
DateTime startDateTime;
DateTime endDateTime;
bool validStartDate = DateTime.TryParse(startDate, out startDateTime);
bool validEndDate = DateTime.TryParse(endDate, out endDateTime);
// If the start date and end date are both provided, only return results that fall within the specified range.
if (validStartDate && validEndDate)
{
return _data.Where(x => x.Date >= startDateTime && x.Date <= endDateTime);
}
// If only the start date is provided, return results that occurred on or after that date.
if (validStartDate)
{
return _data.Where(x => x.Date >= startDateTime);
}
// If only the end date is provided, return results that occurred on or before that date.
if (validEndDate)
{
return _data.Where(x => x.Date <= endDateTime);
}
// If neither date is provided, return all results.
return _data;
}
在上面的示例代码中,我们使用[FromQuery]注释来将查询字符串参数映射到函数参数。startDate和endDate参数都具有默认值为null,以便它们在没有传递值的情况下成为可选参数。我们还在函数内部检查了这些参数,以确定它们是否包含有效的日期值。
最后,我们使用数据集*_data*返回筛选后的结果。如果没有传递任何参数,则返回所有记录。