Loading... ## ASP.NET Core 2.x 在`Startup.cs`中设置 ```csharp /// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddJsonOptions(options => { //设置输出snake_case风格 options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() }; //设置输出camelCase风格 // options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new CamelCaseNamingStrategy() }; //默认为PascalCase风格 //options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new DefaultNamingStrategy() }; //包含时区信息 options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //包含Null值的序列化 options.SerializerSettings.NullValueHandling = NullValueHandling.Include; }); } ``` ## ASP.NET Core 3.x 在`Startup.cs`中设置 ```csharp /// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(options => { //设置输出snake_case风格 options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() }; //设置输出camelCase风格 // options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new CamelCaseNamingStrategy() }; //默认为PascalCase风格 //options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new DefaultNamingStrategy() }; //包含时区信息 options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //包含Null值的序列化 options.SerializerSettings.NullValueHandling = NullValueHandling.Include; }); } ``` ##### 另外需要说一下`Swagger`的支持,在`ASP.NET Core 3.0`之前,`Swagger`默认的序列化工具使用`Newtonsoft.Json`,所以配置了`Newtonsoft.Json`的全局输出风格后`Swagger`界面的输出也会一致。但是在`ASP.NET Core 3.0`时,由于`ASP.NET Core 3.x`内置了`System.Text.Json`,`Swagger(Swashbuckle>=5.0.0) `默认使用`System.Text.Json`进行序列化操作,所以如果想使`Swagger`继续使用`Newtonsoft.Json`需要额外配置 * 引入`Swashbuckle.AspNetCore.Newtonsoft` 在`Startup.cs`中 ```csharp /// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { //Swagger序列化操作使用Newtonsoft.Json services.AddSwaggerGenNewtonsoftSupport(); } ``` ## Reference * [Swashbuckle.AspNetCore](https://github.com/domaindrivendev/Swashbuckle.AspNetCore#systemtextjson-stj-vs-newtonsoft) 最后修改:2020 年 09 月 22 日 © 允许规范转载 赞 0 如果觉得我的文章对你有用,请随意赞赏