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

ASP.NET Core控制器解析错误:如何直接接收JSON字符串?

解决ASP.NET Core端点直接接收未解析JSON字符串的问题

问题原因

你用[FromBody]string jsonData时,ASP.NET Core的模型绑定会尝试把请求体的JSON对象解析成string类型——但JSON对象(比如{"key":"value"})本身不是合法的JSON字符串(JSON字符串需要被双引号包裹,比如"{\"key\":\"value\"}"),所以会抛出解析错误。

方案一:直接读取Request.Body(最简单)

跳过模型绑定,直接从请求体读取原始内容,完全避免框架的解析操作:

[HttpPost]
[Route("pushjson/{channelCode}")]
public async Task<string> PushJson(string channelCode)
{
    using var reader = new StreamReader(Request.Body, Encoding.UTF8);
    var jsonData = await reader.ReadToEndAsync();
    return await mediator.Send(new PushJsonCommand(channelCode, jsonData));
}

方案二:自定义InputFormatter(保留[FromBody]写法)

如果希望保留[FromBody]string的参数写法,可以自定义输入格式化器,让它直接返回原始请求体字符串,不解析JSON:

  1. 实现自定义InputFormatter:
public class RawStringInputFormatter : InputFormatter
{
    public RawStringInputFormatter()
    {
        // 支持application/json和text/plain类型的请求
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/plain"));
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
    {
        using var reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8);
        var rawContent = await reader.ReadToEndAsync();
        return await InputFormatterResult.SuccessAsync(rawContent);
    }

    protected override bool CanReadType(Type type)
    {
        // 只处理string类型的参数
        return type == typeof(string);
    }
}
  1. 在Program.cs中注册这个格式化器:
builder.Services.AddControllers(options =>
{
    // 插入到格式化器列表最前面,优先使用
    options.InputFormatters.Insert(0, new RawStringInputFormatter());
});

注册完成后,你原来的Action代码可以保持不变,框架会直接把原始JSON字符串传入jsonData参数,不会再做解析操作。

为什么不用JObject?

你之前用JObject接收再序列化的方式,会让框架先把JSON解析成JObject对象,之后又序列化回字符串,这两步都是不必要的性能开销,上面的两种方案都能避免这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 08:55:02