4
votes

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)

1
You can try to achieve it with an ActionFilter, and this SO thread discussed a similar requirement, you can refer to it.Fei Han

1 Answers

1
votes

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