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

ASP.NET MVC 5单个端点自定义System.Text.Json反序列化器未生效问题

解决ASP.NET MVC 5单个端点处理大型JSON Payload的问题

为什么你的System.Text.Json转换器没生效

ASP.NET MVC 5默认使用**Newtonsoft.Json(Json.NET)**作为序列化/反序列化组件,而System.Text.Json是.NET Core 3.0之后才引入的。你给Foo类添加的System.Text.Json相关转换器属性,MVC 5的默认模型绑定机制完全不会识别,所以根本不会触发。

两种可行的解决方案

方案1:手动用System.Text.Json处理请求(绕开默认模型绑定)

直接在目标Action中读取请求流,手动用System.Text.Json反序列化,完全控制配置,不影响全局:

[HttpPost]
public async Task<ActionResult> ProcessLargeFoo()
{
    // 重置请求流位置(避免读取到空内容)
    Request.InputStream.Position = 0;
    
    using var streamReader = new StreamReader(Request.InputStream);
    var jsonContent = await streamReader.ReadToEndAsync();
    
    // 配置System.Text.Json的反序列化选项,设置适合大型Payload的参数
    var serializerOptions = new JsonSerializerOptions
    {
        MaxDepth = 64, // 根据实际JSON结构深度调整
        PropertyNameCaseInsensitive = true, // 匹配MVC默认的大小写不敏感行为
        // 若需要自定义转换器,可在这里添加
        // Converters = { new FooConverter() }
    };
    
    var foo = JsonSerializer.Deserialize<Foo>(jsonContent, serializerOptions);
    
    // 后续业务逻辑处理
    return Ok("处理完成");
}

方案2:针对单个Action配置Newtonsoft.Json的高限制(贴合MVC5默认机制)

既然MVC5默认用Newtonsoft.Json,不如直接给目标Action单独设置更高的反序列化限制,避免全局修改:

  1. 自定义ModelBinder:
public class LargeFooModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;
        request.InputStream.Position = 0;
        
        using var reader = new StreamReader(request.InputStream);
        var json = reader.ReadToEnd();
        
        // 设置针对大型Payload的反序列化参数
        var jsonSettings = new JsonSerializerSettings
        {
            MaxItemsInObjectGraph = 100000, // 替代全局的aspnet:MaxJsonDeserializerMembers
            MaxDepth = 64,
            MissingMemberHandling = MissingMemberHandling.Ignore // 保持和MVC默认一致
        };
        
        return JsonConvert.DeserializeObject<Foo>(json, jsonSettings);
    }
}
  1. 在Action参数上绑定这个ModelBinder:
[HttpPost]
public ActionResult ProcessLargeFoo([ModelBinder(typeof(LargeFooModelBinder))] Foo foo)
{
    // 业务逻辑处理
    return Ok();
}

额外说明

不建议在MVC5中全局替换为System.Text.Json,这需要自定义ValueProviderFactory或ModelBinderProvider,配置复杂且容易引入兼容性问题,针对单个Action做局部处理是更稳妥的生产环境方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 13:19:54