WebAPI按ID查询未找到值时未返回正确状态码求助
问题分析:Get接口未找到数据时返回200而非404的原因
你的代码核心问题出在对Dapper QueryAsync方法返回值的判断逻辑上,具体如下:
1. 错误根源:Dapper的返回值特性
Dapper的QueryAsync<T>方法在存储过程无匹配数据时,不会返回null,而是返回一个空的IEnumerablecaseInfo == null永远为false,所以无论有没有数据都会执行Ok(caseInfo)分支,空集合序列化后就是{},状态码自然是200。
2. 修复代码
修改判断逻辑,检查集合是否包含元素即可,以下是两种可行的修复方式:
方式一:转换为List后判断
[HttpGet("{SessionID}")] [ProducesResponseType(typeof(List<CaseInformation>), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult<List<CaseInformation>>> GetCaseInformationByID(string SessionID) { using var connection = new SqlConnection(_config.GetConnectionString("SQlServer")); var caseInfoList = (await connection.QueryAsync<CaseInformation>( "GetCaseInformationByIDSP", new { SessionID = SessionID }, commandType: CommandType.StoredProcedure )).ToList(); return caseInfoList.Any() ? Ok(caseInfoList) : NotFound(); }
方式二:直接用LINQ的Any()判断
[HttpGet("{SessionID}")] [ProducesResponseType(typeof(List<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.Any() ? Ok(caseInfo) : NotFound(); }
3. 额外优化提示
- 修正
ProducesResponseType的类型:原代码中200状态码标注的是typeof(CaseInformation),但实际返回的是List<CaseInformation>,建议改成typeof(List<CaseInformation>),让接口文档更准确。 - 确认存储过程
GetCaseInformationByIDSP的行为:确保它在无匹配ID时确实不返回任何行,而不是返回包含空值的行,否则判断逻辑依然会失效。
内容的提问来源于stack exchange,提问作者Jerry Trac
相关产品推荐
相关产品推荐

