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

ASP.NET Core Web API如何兼容CCX单引号格式的JSON请求?

解决ASP.NET Core识别单引号格式JSON的问题

你的ASP.NET Core服务默认仅支持标准JSON格式(属性名和字符串用双引号),而CCX发送的单引号格式不符合JSON规范,导致触发400验证错误。以下两种方案可以解决这个问题:

方案一:改用Newtonsoft.Json并开启单引号支持

这是最简单的方案,利用Newtonsoft.Json内置的单引号解析支持:

  1. 安装NuGet包:
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson

或通过.NET CLI:

dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
  1. 在Program.cs中配置服务,替换默认JSON处理为NewtonsoftJson并允许单引号:
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.AllowSingleQuotes = true;
    });

var app = builder.Build();

// 其他中间件配置...

app.Run();

方案二:自定义System.Text.Json输入格式化器

若想继续使用原生System.Text.Json,可自定义格式化器,先将请求体中的单引号替换为双引号再解析:

  1. 创建自定义输入格式化器类:
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using System.Text;
using System.Text.Json;

public class SingleQuoteJsonInputFormatter : SystemTextJsonInputFormatter
{
    public SingleQuoteJsonInputFormatter(JsonOptions options) : base(options)
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
    {
        using var reader = new StreamReader(context.HttpContext.Request.Body, encoding);
        var rawContent = await reader.ReadToEndAsync();
        
        // 替换单引号为双引号(注:若字符串内容含单引号,此逻辑会误替换,需根据实际场景调整)
        var correctedJson = rawContent.Replace('\'', '"');
        
        using var correctedStream = new MemoryStream(encoding.GetBytes(correctedJson));
        context.HttpContext.Request.Body = correctedStream;
        
        return await base.ReadRequestBodyAsync(context, encoding);
    }
}
  1. 在Program.cs中注册自定义格式化器:
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers(options =>
{
    // 移除默认的SystemTextJson输入格式化器
    var defaultFormatter = options.InputFormatters.OfType<SystemTextJsonInputFormatter>().FirstOrDefault();
    if (defaultFormatter != null)
    {
        options.InputFormatters.Remove(defaultFormatter);
    }
    // 添加自定义格式化器
    options.InputFormatters.Add(new SingleQuoteJsonInputFormatter(options.JsonOptions));
});

var app = builder.Build();

// 其他中间件配置...

app.Run();

注意事项

  • 方案一兼容性更好,Newtonsoft.Json会自动处理字符串内的转义单引号,无需额外逻辑。
  • 方案二中的替换逻辑仅适用于字符串内容不含单引号的场景,若CCX发送的JSON存在带单引号的字符串(如{'name': 'O\'Neil'}),需用正则替换区分属性名的单引号和字符串内的单引号。

CCX发送的请求体示例:

{ 'serverName': 'myServer.domain.com' }

服务原错误响应示例:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-a93e09028c78d685900520cfe2702830-2c271adc36377644-00",
    "errors": {
        "$": [
                 "' is an invalid start of a property name. Expected a '\"'. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
             ]
    }
}

内容的提问来源于stack exchange,提问作者Barış Sakızlı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:30:37