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

搭建API时遇JSON转Model失败及System.Action序列化异常求助

API请求错误排查与解决方案

错误信息与代码详情

初始Postman返回400错误

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-126b1240f4b8ded273f6f4c63fc7e1f6-53d97b7f1d5afc42-00",
    "errors": {
        "$": [
            "The JSON value could not be converted to HostSimulatorLibrary.Models.OutgoingMessageModel. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
        ],
        "message": [
            "The message field is required."
        ]
    }
}

控制器代码

// POST api/Messages
[HttpPost]
public async Task<ActionResult<OutgoingMessageModel>> Post([FromBody] OutgoingMessageModel message )
{
     var output = _data.SendSocketResponse(message);
     return Ok(output);
}

模型代码

namespace HostSimulatorLibrary.Models;

public class OutgoingMessageModel{
    public int RequestID { get; set; }    
    public string? ResultText { get; set; }
}

初始输入JSON

[
   {
    "RequestID":1073388,
    "ResultTX": "TEXT"
   }
]

去掉数组后的错误

System.NotSupportedException: Serialization and deserialization of 'System.Action' instances are not supported. Path: $.MoveNextAction. ---> System.NotSupportedException: Serialization and deserialization of 'System.Action' instances are not supported.

原因分析

初始400错误原因

  1. JSON格式不匹配:输入是数组(外层带[]),但接口接收的是单个OutgoingMessageModel对象,JSON反序列化器无法将数组转换为单个对象,触发格式错误。
  2. 字段名不匹配:输入中的ResultTX与模型定义的ResultText字段名不一致,即使格式正确也无法正确赋值。
  3. "message字段必填"误导:实际是JSON格式错误导致参数绑定失败,并非模型需要message字段。

去掉数组后的序列化错误原因

控制器方法标记为async,但调用_data.SendSocketResponse(message)时未使用await,导致output实际是Task<OutgoingMessageModel>类型而非目标模型。JSON序列化器尝试序列化Task对象时,遇到其内部的MoveNextAction委托成员,而序列化器不支持委托类型的序列化,因此抛出错误。


解决方案

解决初始400错误

  1. 修正输入JSON格式:去掉外层数组括号,改为单个对象:
    {
      "RequestID": 1073388,
      "ResultText": "TEXT"
    }
    
  2. 修正字段名:将输入中的ResultTX改为与模型一致的ResultText。

解决序列化错误

在控制器中对异步方法调用添加await,确保获取到实际的模型对象而非Task:

// POST api/Messages
[HttpPost]
public async Task<ActionResult<OutgoingMessageModel>> Post([FromBody] OutgoingMessageModel message )
{
     var output = await _data.SendSocketResponse(message); // 添加await
     return Ok(output);
}

额外检查

如果SendSocketResponse返回的模型本身包含Action/Func等委托成员,需在对应字段上添加[JsonIgnore]特性,阻止序列化该字段:

public class YourOutputModel
{
    // 其他业务字段
    [JsonIgnore]
    public Action MoveNextAction { get; set; } // 标记为忽略序列化
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:35:50