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

Net Core 6中能否为单个控制器方法重定义输出格式化器?

针对单个API方法返回原始未格式化JSON的解决方案

方法一:直接返回ContentResult(最简单高效)

不用修改全局格式化器,直接把JArray转成无格式的字符串,通过ContentResult返回即可,完全绕开默认的JSON格式化流程:

[HttpGet("your-raw-endpoint")]
public IActionResult GetRawUnformattedJson()
{
    // 你已经获取到的目标JArray
    JArray targetJArray = GetYourPreparedJArray();
    
    // 用Formatting.None生成无缩进、无换行的原始JSON字符串
    string rawJsonString = targetJArray.ToString(Formatting.None);
    
    // 指定内容类型为application/json,直接返回原始字符串
    return Content(rawJsonString, "application/json");
}

方法二:为单个方法指定自定义输出格式化器

如果你确实需要通过自定义格式化器实现,可以按以下步骤操作:

1. 定义原始JSON输出格式化器

public class RawJsonOutputFormatter : TextOutputFormatter
{
    public RawJsonOutputFormatter()
    {
        // 支持application/json媒体类型
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
        // 支持UTF8和Unicode编码
        SupportedEncodings.Add(Encoding.UTF8);
        SupportedEncodings.Add(Encoding.Unicode);
    }

    // 只处理JArray类型的返回值
    protected override bool CanWriteType(Type type)
    {
        return type == typeof(JArray);
    }

    // 写入原始JSON内容
    public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
    {
        if (context.Object is JArray jArray)
        {
            var response = context.HttpContext.Response;
            // 输出无格式的JSON字符串
            return response.WriteAsync(jArray.ToString(Formatting.None), selectedEncoding);
        }
        return Task.CompletedTask;
    }
}

2. 在目标方法中使用该格式化器

直接在返回ObjectResult时指定仅使用这个自定义格式化器,避免全局影响:

[HttpGet("your-formatted-endpoint")]
public IActionResult GetRawJsonWithCustomFormatter()
{
    JArray targetJArray = GetYourPreparedJArray();
    
    return new ObjectResult(targetJArray)
    {
        // 仅对该请求应用自定义格式化器
        Formatters = new List<IOutputFormatter> { new RawJsonOutputFormatter() }
    };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:05:20