ASP.NET Core 3.1:仅在部分控制器中使用Newtonsoft JSON
实现ASP.NET Core 3.1中部分控制器使用Newtonsoft JSON序列化器
要实现仅让指定控制器使用Newtonsoft JSON,其余控制器默认用System.Text.Json,可按以下步骤操作:
1. 定义标记特性
创建一个自定义特性,用于标记需要使用Newtonsoft的控制器:
[AttributeUsage(AttributeTargets.Class)] public class UseNewtonsoftJsonAttribute : Attribute { }
2. 全局配置序列化器
在Startup.cs的ConfigureServices方法中,先全局启用System.Text.Json作为默认序列化器,同时添加Newtonsoft的配置(但不全局替换):
services.AddControllers(options => { // 配置全局System.Text.Json的序列化规则(按需调整) options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve; options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; }) // 添加Newtonsoft JSON的配置,后续仅对标记特性的控制器生效 .AddNewtonsoftJson(options => { // 配置Newtonsoft的序列化规则(按需调整) options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); });
3. 添加控制器约定实现精准切换
创建一个控制器约定类,自动为标记了[UseNewtonsoftJson]的控制器替换序列化器:
public class NewtonsoftJsonControllerConvention : IControllerModelConvention { public void Apply(ControllerModel controller) { if (controller.ControllerType.GetCustomAttribute<UseNewtonsoftJsonAttribute>() != null) { // 为该控制器添加结果过滤器,替换为Newtonsoft格式化器 controller.Filters.Add(new ServiceFilterAttribute(typeof(NewtonsoftJsonResultFilter))); } } } public class NewtonsoftJsonResultFilter : IResultFilter { private readonly NewtonsoftJsonOutputFormatter _newtonsoftFormatter; public NewtonsoftJsonResultFilter(IEnumerable<IOutputFormatter> formatters) { _newtonsoftFormatter = formatters.OfType<NewtonsoftJsonOutputFormatter>().FirstOrDefault(); } public void OnResultExecuting(ResultExecutingContext context) { if (context.Result is ObjectResult objectResult) { // 清除原有格式化器,添加Newtonsoft的格式化器 objectResult.Formatters.Clear(); if (_newtonsoftFormatter != null) { objectResult.Formatters.Add(_newtonsoftFormatter); } } } public void OnResultExecuted(ResultExecutedContext context) { // 无需额外处理 } }
然后在ConfigureServices的AddControllers配置中注册这个约定:
services.AddControllers(options => { options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve; options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; // 注册控制器约定 options.Conventions.Add(new NewtonsoftJsonControllerConvention()); }) .AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); });
4. 标记需要迁移的控制器
在暂未迁移的控制器上添加[UseNewtonsoftJson]特性,该控制器的所有Action都会使用Newtonsoft JSON序列化:
[UseNewtonsoftJson] public class LegacyDataController : ControllerBase { [HttpGet("legacy-data")] public IActionResult GetLegacyData() { return Ok(new { Id = 1, Name = "LegacyItem", RelatedItems = new List<object> { new { Id = 2, Name = "Related" } } }); } }
注意事项
- 如果需要处理输入JSON的反序列化(比如POST请求接收JSON),可以参照上述逻辑,为标记特性的控制器添加
NewtonsoftJsonInputFormatter,确保请求解析也使用Newtonsoft。 - 所有未标记
[UseNewtonsoftJson]的控制器,默认会使用System.Text.Json进行序列化和反序列化。
内容的提问来源于stack exchange,提问作者user2033412
相关产品推荐
相关产品推荐

