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

.NET 7 Webhook接口如何识别并接收两种不同请求体?

解决方案

直接用object作为参数时,ASP.NET Core会将JSON请求体默认反序列化为JsonElement(System.Text.Json)或JObject(Newtonsoft.Json),无法直接识别目标类型,你可以通过以下两种方式实现请求体类型识别:

方法1:尝试反序列化到目标类

先接收原始JSON字符串,依次尝试反序列化为SignupMatch和Proposal,根据反序列化是否成功判断类型:

using System.Text.Json;

[HttpPost]
public IActionResult Post([FromBody] string json)
{
    try
    {
        // 尝试反序列化为SignupMatch
        if (JsonSerializer.Deserialize<SignupMatch>(json) is { } signupMatch)
        {
            // 调用SignupMatch对应的服务逻辑
            // _signupMatchService.Process(signupMatch);
            return Ok("处理SignupMatch请求");
        }

        // 尝试反序列化为Proposal
        if (JsonSerializer.Deserialize<Proposal>(json) is { } proposal)
        {
            // 调用Proposal对应的服务逻辑
            // _proposalService.Process(proposal);
            return Ok("处理Proposal请求");
        }

        // 两种类型都匹配失败
        return BadRequest("无法识别请求体类型");
    }
    catch (JsonException ex)
    {
        return BadRequest($"JSON格式错误:{ex.Message}");
    }
    catch (Exception ex)
    {
        return BadRequest($"处理失败:{ex.Message}");
    }
}

方法2:通过特征属性判断类型

先将请求体解析为JsonDocument,检查是否包含目标类的特征属性(比如SignupMatch有Matches字段,Proposal有mother字段),再针对性反序列化:

using System.Text.Json;

[HttpPost]
public IActionResult Post([FromBody] JsonDocument jsonDoc)
{
    try
    {
        var root = jsonDoc.RootElement;

        // 检查是否包含SignupMatch的特征属性(比如Matches)
        if (root.TryGetProperty("Matches", out _))
        {
            var signupMatch = root.Deserialize<SignupMatch>();
            // 处理SignupMatch逻辑
            return Ok("处理SignupMatch请求");
        }

        // 检查是否包含Proposal的特征属性(比如mother)
        if (root.TryGetProperty("mother", out _))
        {
            var proposal = root.Deserialize<Proposal>();
            // 处理Proposal逻辑
            return Ok("处理Proposal请求");
        }

        return BadRequest("无法识别请求体类型");
    }
    catch (JsonException ex)
    {
        return BadRequest($"JSON格式错误:{ex.Message}");
    }
    catch (Exception ex)
    {
        return BadRequest($"处理失败:{ex.Message}");
    }
}

注意事项

  • 如果使用Newtonsoft.Json替代System.Text.Json,只需将JsonSerializer替换为JsonConvert,JsonDocument替换为JObject即可。
  • 确保两个模型类的特征属性不会重叠,避免误判;如果有重叠属性,可以组合多个特征属性进行判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:12:22