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

C#处理Telnyx API回调JSON时出现解析异常如何解决

问题根因

  1. 模型结构定义错误:Root、Data、Payload、Meta均为myDeserializedClass的嵌套类,外层myDeserializedClass无任何公开属性,请求JSON无法正确绑定到该类型实例。
  2. 多余的手动反序列化逻辑:ASP.NET 自带的模型绑定机制会自动将POST请求体的JSON反序列化为对应参数类型的实例,调用json.ToString()得到的是该类型的全限定类名字符串,并非合法JSON,直接触发反序列化报错。
  3. 缺少[FromBody]标记:POST请求的JSON内容存放在请求体中,不加该标记时模型绑定会默认从表单字段读取参数,无法匹配到对应数据。

如果不想调整现有嵌套类结构,也可以直接将控制器参数类型指定为myDeserializedClass.Root,同样可以实现正确绑定。

修复方案

步骤1:调整模型定义

移除无意义的外层myDeserializedClass,将所有业务类定义为顶级类:

public class Payload
{
    public int call_duration_secs { get; set; }
    public string connection_id { get; set; }
    public string direction { get; set; }
    public string fax_id { get; set; }
    public string from { get; set; }
    public string media_url { get; set; }
    public int page_count { get; set; }
    public bool? partial_content { get; set; }
    public string status { get; set; }
    public string to { get; set; }
    public string user_id { get; set; }
}

public class Data
{
    public string event_type { get; set; }
    public string id { get; set; }
    public DateTime occurred_at { get; set; }
    public Payload payload { get; set; }
    public string record_type { get; set; }
}

public class Meta
{
    public int attempt { get; set; }
    public string delivered_to { get; set; }
}

public class FaxWebhookRoot
{
    public Data data { get; set; }
    public Meta meta { get; set; }
}

步骤2:修改控制器逻辑

直接使用根模型作为参数,删除手动反序列化代码,补充[FromBody]标记:

[HttpPost]
public IActionResult InboundFax([FromBody] FaxWebhookRoot payload)
{
    try
    {
        // 直接使用payload对象读取业务字段即可,示例:
        // var faxUrl = payload.data.payload.media_url;
        // var sender = payload.data.payload.from;
        return Content("OK");
    }
    catch(Exception ex)
    {
        return Content(ex.ToString());
    }
}

可选优化

如果需要符合C#帕斯卡命名规范,可以给属性添加序列化特性适配JSON小写蛇形命名:

// 若使用Newtonsoft.Json,加 [JsonProperty("event_type")]
// 若使用System.Text.Json,加 [JsonPropertyName("event_type")]
public string EventType { get; set; }

如果是ASP.NET Core 3.0+版本且使用Newtonsoft.Json作为序列化组件,需要在启动配置中添加AddNewtonsoftJson()配置,避免模型绑定失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:45:03