当我执行 HTTPGet[按 ID] 时,如果在数据库中找不到该 ID,我希望它返回一个错误代码 Not Found 但是我得到这个代码 200 和“{}”的响应值。
我做错了什么?
[HttpGet("{SessionID}")]
[ProducesResponseType(typeof(CaseInformation), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<List<CaseInformation>>> GetCaseInformationByID(string SessionID)
{
using var connection = new SqlConnection(_config.GetConnectionString("SQlServer"));
var caseInfo = await connection.QueryAsync<CaseInformation>("GetCaseInformationByIDSP", new { SessionID = SessionID }, commandType: CommandType.StoredProcedure);
return caseInfo == null ? NotFound() : Ok(caseInfo);
}
您正在检查
caseInfo
是否为空。即使在数据库中找不到 ID,caseInfo
也不为空。您需要检查caseInfo
列表是否为空
if (caseInfo.Count == 0)
{
return NotFound();
}
return Ok(caseInfo);
if (caseInfo != null && caseInfo.Any())
{
return Ok(caseInfo);
}
else
return NotFound();