using IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson; using IRaCIS.Core.Application.Helper; using IRaCIS.Core.Domain.Share; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Globalization; using System.Text.Json; using Newtonsoft.Json.Serialization; namespace IRaCIS.Core.API { public static class NewtonsoftJsonSetup { public static void AddNewtonsoftJsonSetup(this IMvcBuilder builder, IServiceCollection services) { services.AddHttpContextAccessor(); services.AddScoped(); services.AddScoped(); services.AddScoped(); builder.AddNewtonsoftJson(options => { //大驼峰 //options.SerializerSettings.ContractResolver = new DefaultContractResolver(); //小驼峰 //options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //处理返回给前端 可空类型 给出默认值 比如in? 为null 设置 默认值0 options.SerializerSettings.ContractResolver = new NullToEmptyStringResolver(); // 设置时间格式 isEn_US? "MM/dd/yyyy HH:mm:ss" : //options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; //二者只能取其一 //options.SerializerSettings.Converters.Add(new MyDateTimeConverter()); //options.SerializerSettings.Converters.Add(new MyNullableDateTimeConverter()); //必须放在后面 options.SerializerSettings.Converters.Add(services.BuildServiceProvider().GetService()); }) .AddControllersAsServices()//动态webApi属性注入需要 .ConfigureApiBehaviorOptions(o => { o.SuppressModelStateInvalidFilter = true; //自己写验证 ////这里是自定义验证结果和返回状态码 因为这里是在[ApiController]控制器层校验,动态webApi的不会校验 所以需要单独写一个Filter //o.InvalidModelStateResponseFactory = (context) => //{ // var error = context.ModelState .Keys // .SelectMany(k => context.ModelState[k].Errors) // .Select(e => e.ErrorMessage) // .ToArray(); //return new JsonResult(ResponseOutput.NotOk("The inputs supplied to the API are invalid. " + JsonConvert.SerializeObject( error))); //}; }); Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings(); JsonConvert.DefaultSettings = new Func(() => { //日期类型默认格式化处理 setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; return setting; }); } } }