You need to enable JavaScript to run this app. .NET Web API调用SQL Server存储过程仅返回True 如何返回预期JSON响应
优惠活动
大模型
产品
解决方案
定价
更多

.NET Web API调用SQL Server存储过程仅返回True 如何返回预期JSON响应

问题根因

现有服务层DoTacVerify方法返回类型为bool,控制器直接将该布尔值传入Ok()方法返回,因此Postman只会收到True;同时未定义对应预期响应结构的实体,也未从存储过程返回的结果中提取客户ID组装响应。


调整步骤

1. 定义符合预期响应结构的DTO实体

新增两个类用于映射响应结构,可放在模型层下:

// 响应状态DTO
public class ApiResponseStatus
{
    // 若需要返回00格式的编码,将类型改为string,赋值为"00"即可
    public int code { get; set; }
    public string response_message { get; set; }
}

// TAC验证外层响应DTO
public class TacVerifyResponseDto
{
    // 对应预期JSON中的"customer _id"字段(空格为原示例写法,若为笔误可去掉空格)
    [JsonPropertyName("customer _id")]
    public string customer_id { get; set; }
    public ApiResponseStatus response { get; set; }
}

注意:若项目使用Newtonsoft.Json做序列化,将[JsonPropertyName]替换为[JsonProperty]特性。JSON规范不支持带前导零的数字,示例中"code": 00实际序列化后会转为0,若需保留00格式请将code改为string类型。

2. 重写服务层方法的返回逻辑

修改DoTacVerify方法的返回类型,从结果集中提取客户ID,组装对应响应:

// 返回类型改为自定义DTO,不再返回bool
public TacVerifyResponseDto DoTacVerify(TacVerify_Model objsso)
{            
    // 初始化默认失败响应(用于验证不通过的场景)
    var verifyResponse = new TacVerifyResponseDto
    {
        customer_id = null,
        response = new ApiResponseStatus
        {
            code = 1,
            response_message = "TAC验证失败"
        }
    };

    SqlParameter[] parm =
    {
        new SqlParameter("temp_token", objsso.temp_token),
        new SqlParameter("tac", objsso.tac)
    };

    var connectionString = System.Configuration.ConfigurationManager.
    ConnectionStrings["_cs"].ConnectionString;
    dbUtil db = new dbUtil(connectionString);
    DataSet ds = db.Select("SSO_TAC_VERIFY", parm);

    // 校验结果集,提取客户ID
    if (ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
    {
        // 从存储过程返回的行中读取CUSTOMER_ID
        string customerId = ds.Tables[0].Rows[0]["CUSTOMER_ID"].ToString().Trim();
        // 替换为成功响应
        verifyResponse = new TacVerifyResponseDto
        {
            customer_id = customerId,
            response = new ApiResponseStatus
            {
                code = 0,
                response_message = "Success"
            }
        };
    }

    return verifyResponse;
}

原代码中遍历DataTable设置布尔值的逻辑属于冗余判断,只要结果集行数大于0即代表TAC验证通过,直接取第一行的CUSTOMER_ID即可。

3. 控制器无需核心修改

现有控制器逻辑可直接复用,Ok()方法会自动将返回的DTO序列化为JSON格式:

[Route("api/Account/Verify_tac")]
[HttpPost]
public IHttpActionResult verifyTac(TacVerify_Model sso)
{
    SSOService verify_tac = new SSOService();
    ModelState.Clear();
    return Ok(verify_tac.DoTacVerify(sso));
}

可选优化点

  • 修正存储过程配置:原存储过程中SET NOCOUNT OFF会额外返回受影响行数的结果集,可能干扰db.Select方法解析数据,建议改为SET NOCOUNT ON;。
  • 修正字段名笔误:预期JSON中"customer _id"的空格大概率为书写错误,若实际不需要空格,可去掉DTO特性中的空格,避免前端对接出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 14:06:03