You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ASP.NET Get API在响应体中返回布尔值?

解决Get API返回200时响应体带True的问题

修改后的API代码

[SwaggerResponse(HttpStatusCode.OK, "返回布尔值True", typeof(bool))]
[SwaggerResponse(HttpStatusCode.BadRequest)]
[HttpGet]
[Route("tenants/{tenantId:Guid}/cpgofferstatus/{advertOfferId:Guid}")]
public async Task<HttpResponseMessage> statusCheck([FromUri] Guid tenantId, [FromUri] Guid advertOfferId)
{
   var result = await _digitalOffersDataProvider.CpgOfferStatus(tenantId, advertOfferId).ConfigureAwait(false);
           
   return result 
       ? Request.CreateResponse(HttpStatusCode.OK, result) 
       : Request.CreateResponse(HttpStatusCode.BadRequest);
}

关键修改说明

  1. 添加响应内容:将原代码中仅返回状态码的Request.CreateResponse调用,改为传入result作为响应体内容的重载方法。当result为true时,ASP.NET会自动将布尔值序列化为JSON格式的true返回在响应体中。
  2. 更新Swagger注释:补充SwaggerResponse的响应类型说明,让API文档明确展示200状态码对应的响应体结构。

额外提示

数据提供者方法CpgOfferStatus中的catch块未处理异常(仅注释了抛出逻辑),若进入异常分支后没有后续返回逻辑,会导致编译错误或方法无法返回有效值,建议补充异常处理,例如:

catch (Exception ex)
{
    // 可根据需求记录日志后抛出异常,或返回默认值
    _logger.LogError(ex, "查询CpgOffer状态出错");
    throw;
}

内容的提问来源于stack exchange,提问作者duckgame

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:15:21