SQL Server WebAPi is not returning correct status code for Value not found

lymnna71  于 2023-03-07  发布在  其他
关注(0)|答案(2)|浏览(115)

When I do a HTTPGet[By ID], I want it to return an error code of Not Found if the ID is not found in the database however I am getting this code 200 and the response value of "{}".

What am I doing wrong?

[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);
       
    }
b4qexyjb

b4qexyjb1#

You are checking caseInfo is null or not. caseInfo is not null even when the ID is not found in the database. You need to check whether the caseInfo list is empty or not.

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

nimxete22#

if (caseInfo != null && caseInfo.Any())
        {
            return Ok(caseInfo);
        }
        else
            return NotFound();

相关问题