ASP.NET Core 3.1:仅在某些控制器中使用 Newtonsoft JSON

问题描述 投票:0回答:1

我有一个使用的 ASP.NET Core 3.1 应用程序

services.AddControllers().AddNewtonsoftJson();

使用 Newtonsoft JSON 序列化器。不幸的是我无法一步完全切换到

System.Text.Json

有没有办法放置像这样的属性

[NewtonsoftJson]
public class MyController : Controller
{
   // ...

在那些我还无法迁移的控制器上——并且仅对这些控制器使用 Newtonsoft?

asp.net-core serialization json.net system.text.json
1个回答
0
投票

根据您的描述,我建议您可以考虑使用ActionFilterAttribute来实现您的要求。

如下:

public class NewtonsoftJsonFormatterAttribute : ActionFilterAttribute
{
   public override void OnActionExecuted(ActionExecutedContext context)
   {
       if (context.Result is ObjectResult objectResult)
       {
           var jsonOptions = context.HttpContext.RequestServices.GetService<IOptions<MvcNewtonsoftJsonOptions>>();
 
            objectResult.Formatters.RemoveType<SystemTextJsonOutputFormatter>();
            objectResult.Formatters.Add(new NewtonsoftJsonOutputFormatter(
                jsonOptions.Value.SerializerSettings,
                context.HttpContext.RequestServices.GetRequiredService<ArrayPool<char>>(),
                context.HttpContext.RequestServices.GetRequiredService<IOptions<MvcOptions>>().Value));
        }
        else
        {
             base.OnActionExecuted(context);
        }
    }
}

更多详情,可以参考这篇文章

© www.soinside.com 2019 - 2024. All rights reserved.