Search code examples
asp.net-coreserializationjson.netsystem.text.json

ASP.NET Core 3.1: Use Newtonsoft JSON only in some controllers


I have an ASP.NET Core 3.1 application where I use

services.AddControllers().AddNewtonsoftJson();

to use the Newtonsoft JSON serializer. Unfortunately I cannot switch completely to System.Text.Json in one step.

Is there a way to put an attribute like

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

on those controllers that I could not yet migrate -- and only use Newtonsoft for these controllers?


Solution

  • According to your description, I suggest you could consider using the ActionFilterAttribute to achieve your requirement.

    Like below :

    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);
            }
        }
    }
    

    More details, you could refer to this article.