10

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)

2

1 Answer 1

4

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

You might want to post this answer on the question I've linked as a duplicate, as this question is likely to get closed.
@IanKemp There's already a good answer on the duplicate (also pointed by Fei Han), which I adapted for this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.