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

ASP.NET Core 3.1 Web API单个POST接口接收多类型JSON返回404如何解决

问题根因
  • 模型绑定失败:之前的代码使用[FromBody] string jsonString接收参数,ASP.NET Core默认模型绑定规则下:
    • 若请求头Content-Type设为text/plain,默认绑定器不支持该媒体类型的[FromBody]绑定,会直接跳过绑定,参数为空导致路由匹配失败返回404
    • 若请求头Content-Type设为application/json,绑定器会尝试将请求体的JSON对象反序列化为字符串类型,类型不匹配导致绑定失败,同样返回404
  • 路由不匹配:若请求的URL和控制器/Action配置的路由规则不一致,也会直接返回404
解决方法

你后续改用System.Text.Json.JsonElement的思路是正确的,按以下步骤调整即可:

1. 修正控制器与Action配置

确保控制器添加了[ApiController]特性,路由配置和你请求的URL匹配,示例如下:

using Microsoft.AspNetCore.Mvc;
using System.Text.Json;

[ApiController]
// 路由规则对应请求地址为 POST https://localhost:44307/api/[控制器名]
// 例如控制器名为DataController,请求地址就是https://localhost:44307/api/Data
[Route("api/[controller]")]
public class DataController : ControllerBase
{
    private readonly IDataRepository _dataRepository;
    private readonly ILogger<DataController> _logger;

    // 构造注入依赖服务
    public DataController(IDataRepository dataRepository, ILogger<DataController> logger)
    {
        _dataRepository = dataRepository;
        _logger = logger;
    }

    [HttpPost]
    public async Task<IActionResult> Post([FromBody] JsonElement root)
    {
        try
        {
            // 安全校验objectType字段,避免不存在时抛出异常
            if (!root.TryGetProperty("objectType", out var typeProperty) 
                || typeProperty.ValueKind != JsonValueKind.String)
            {
                return BadRequest("请求缺少合法的objectType字段");
            }
            string messageType = typeProperty.GetString()?.ToLower() ?? string.Empty;

            string response = messageType switch
            {
                "type1" => await _dataRepository.InsertType1Record(root),
                "type2" => await _dataRepository.InsertType2Record(root),
                "type3" => await _dataRepository.InsertType3Record(root),
                _ => BadRequest($"不支持的objectType类型:{messageType}")
            };

            return Ok(response);
        }
        catch (Exception e)
        {
            _logger.LogError(e, "处理请求发生异常");
            return BadRequest($"请求处理失败:{e.Message}");
        }
    }
}

2. 调整Fiddler请求配置

将请求头中的content-type: text/plain改为Content-Type: application/json,请求URL和你配置的路由规则保持一致即可。

可选优化

如果后续需要处理的类型越来越多,可以用策略模式将每个类型的处理逻辑抽为独立的实现类,避免大量分支判断,提升代码可维护性。
如果需要继续使用Newtonsoft.Json,直接将Action参数改为[FromBody] JObject root即可,无需先接收字符串再解析,同样可以正常绑定任意结构的JSON对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:36:03