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

.NET 6.0 Minimal API如何配置NewtonsoftJson替代System.Text.Json

解决.NET 6 Minimal API替换Newtonsoft.Json序列化的问题

问题原因

Minimal API默认的请求/响应序列化逻辑完全独立于MVC/控制器相关的配置,你单独配置JsonSerializerSettings或者仅添加AddNewtonsoftJson都不会生效:前者系统默认不会读取,后者仅作用于Controller体系的接口,对Minimal API的MapGet/MapPost等原生端点无效。

方案1:纯Minimal API实现(无MVC依赖)

不需要引入MVC相关组件,只需要安装Newtonsoft.Json NuGet包,自定义序列化/反序列化扩展方法即可:

  1. 安装NuGet包
Install-Package Newtonsoft.Json
  1. 定义公用的序列化配置和扩展方法
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text;

public static class NewtonsoftJsonExtensions
{
    // 统一配置序列化规则,和你之前的要求对齐
    private static readonly JsonSerializerSettings _defaultSettings = new JsonSerializerSettings
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        Formatting = Formatting.Indented,
        ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new CamelCaseNamingStrategy()
        },
        Converters = 
        {
            new StringEnumConverter
            {
                NamingStrategy = new CamelCaseNamingStrategy()
            }
        }
    };

    // 响应序列化扩展
    public static IResult NewtonsoftJson<T>(T data, JsonSerializerSettings? settings = null)
    {
        var json = JsonConvert.SerializeObject(data, settings ?? _defaultSettings);
        return Results.Content(json, "application/json; charset=utf-8");
    }

    // 请求反序列化扩展
    public static async Task<T?> ReadFromNewtonsoftJsonAsync<T>(this HttpRequest request, JsonSerializerSettings? settings = null, CancellationToken cancellationToken = default)
    {
        using var reader = new StreamReader(request.Body, Encoding.UTF8);
        var json = await reader.ReadToEndAsync(cancellationToken);
        return JsonConvert.DeserializeObject<T>(json, settings ?? _defaultSettings);
    }
}
  1. 端点使用示例
// 响应序列化使用
app.MapGet("/test/get", () =>
{
    var result = new { Id = 1, Name = "Test", Status = MyEnum.Active };
    return NewtonsoftJsonExtensions.NewtonsoftJson(result);
});

// 请求反序列化使用
app.MapPost("/test/post", async (HttpRequest req) =>
{
    var input = await req.ReadFromNewtonsoftJsonAsync<YourInputModel>();
    // 业务逻辑处理
    return Results.Ok();
});

这个方案完全基于Minimal API原生体系,没有引入多余依赖,符合纯Minimal API的实现要求。

方案2:兼容控制器模式(允许引入MVC依赖)

如果你项目本身需要同时使用控制器和Minimal API,或者不介意引入MVC相关依赖,可以用AddNewtonsoftJson配置,但是注意这套配置仅对控制器接口生效,Minimal API原生端点还是需要用方案1的扩展方法:

  1. 安装NuGet包
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
  1. 配置服务
builder.Services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        options.SerializerSettings.Formatting = Formatting.Indented;
        options.SerializerSettings.ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new CamelCaseNamingStrategy()
        };
        options.SerializerSettings.Converters.Add(new StringEnumConverter
        {
            NamingStrategy = new CamelCaseNamingStrategy()
        });
    });

// 中间件配置部分要加上控制器路由映射
app.MapControllers();

这种方式下,控制器的接口会自动使用Newtonsoft.Json序列化,Minimal API的原生端点不生效,且引入了MVC整套服务,不属于纯Minimal API实现。

相关疑问说明

直接使用AddControllers().AddNewtonsoftJson的方式,因为引入了完整的MVC服务栈,不属于纯Minimal API的实现,除非你的项目本身就需要用到控制器功能,否则更推荐用方案1的自定义扩展方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:54:04