Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to JsonOutputFormatter in ASP.NET Core 3.1 at Controller Level

I have a custom filter attribute adapted from this answer currently implemented for .NET Core 2.2 that I would like to adapt to 3.1. It references Newtonsoft.JSON and I would prefer to keep it that way for compatibility reasons.

The code follows:

public class AllPropertiesAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext ctx)
    {
        if (!(ctx.Result is ObjectResult objectResult)) return;

        var serializer = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include };
        serializer.Converters.Add(new StringEnumConverter());

        var formatter = new JsonOutputFormatter(serializer, 
                        ctx.HttpContext.RequestServices.GetRequiredService<ArrayPool<char>>());

        objectResult.Formatters.Add(formatter);
    }
}

JsonOutputFormatter is only supported up to .net core 2.2, according to the official documentation; how should I proceed to keep the same behavior under 3.1?

like image 907
OnoSendai Avatar asked Dec 03 '22 09:12

OnoSendai


1 Answers

The equivalent of the old JsonOutputFormatter is NewtonsoftJsonOutputFormatter in the Microsoft.AspNetCore.Mvc.NewtonsoftJson package. It has one minor change, where it will accept an MvcOptions in the constructor as well:

    public NewtonsoftJsonOutputFormatter(
        JsonSerializerSettings serializerSettings,
        ArrayPool<char> charPool,
        MvcOptions mvcOptions)

This is only really affects the behavior via the SuppressOutputFormatterBuffering option. You might be able to resolve it from the RequestServices or you can just create a new one on the fly.

like image 169
Mike Zboray Avatar answered Dec 09 '22 15:12

Mike Zboray