Maguro
Maguro

Reputation: 91

Change System.Text.Json Serialization Options of a single ASP.NET Core API controller or single Action in ASP.NET Core 3

I'm having two controller controllers: ControllerA and ControllerB. The base class of each controller is ControllerBase.

The ControllerA needs to deserialize JSON in the default option

JsonSerializerOptions.IgnoreNullValues = false;

The ControllerB needs to deserialize JSON with option

JsonSerializerOptions.IgnoreNullValues = true;

I know how to set this option global in Startup.cs

services.AddControllers().AddJsonOptions( options => options.JsonSerializerOptions.IgnoreNullValues = true);

But how to set specific deserialize options to Controller or Action? (ASP.NET Core 3 API)

Upvotes: 9

Views: 4365

Answers (1)

McX
McX

Reputation: 1376

As suggested by Fei Han, the straight-forward answer is to use on ControllerB the attribute NullValuesJsonOutput :

public class NullValuesJsonOutputAttribute : ActionFilterAttribute
{
    private static readonly SystemTextJsonOutputFormatter Formatter = new SystemTextJsonOutputFormatter(new JsonSerializerOptions
    {
        IgnoreNullValues = true
    });

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Result is ObjectResult objectResult)
            objectResult.Formatters.Add(Formatter);
    }
}

Upvotes: 3

Related Questions