WebAPI 未返回未找到值的正确状态代码

问题描述 投票:0回答:2

当我执行 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);
       
    }
c# sql-server dapper
2个回答
1
投票

您正在检查

caseInfo
是否为空。即使在数据库中找不到 ID,
caseInfo
也不为空。您需要检查
caseInfo
列表是否为空

 if (caseInfo.Count == 0)
    {
        return NotFound();
    }
    return Ok(caseInfo);

0
投票
if (caseInfo != null && caseInfo.Any())
        {
            return Ok(caseInfo);
        }
        else
            return NotFound();
© www.soinside.com 2019 - 2024. All rights reserved.