'ASP.NET Core 3.1 MVC: setting IgnoreNullValues to true in Startup still renders NULL properties

I have an ASP.NET Core 3.1 project. I am using .AddJsonOptions() in startup with and setting IgnoreNullValues to true.

I've created a simple test, and it still rendering nulls. It does seem like something further down the startup pipeline is overriding my settings.

What can I do to make sure that the JSON configuration is getting set up properly?

Output:

{ "nullString": null, "testSTring": "Test String!" }

App startup:

services.AddControllers()
            .AddJsonOptions(j =>
        {
            j.JsonSerializerOptions.IgnoreNullValues = true;
        });

services.AddControllersWithViews()
            .AddJsonOptions(j =>
            {
                j.JsonSerializerOptions.IgnoreNullValues = true;
            });

// razor templating
services.AddRazorPages()
            .AddPiranhaManagerOptions()
            .AddJsonOptions(j =>
                {
                    j.JsonSerializerOptions.IgnoreNullValues = true;
                });

Test setup:

public class TestObj
{
    public string NullString { get; set; } = null;
    public string TestSTring { get; set; } = "Test String!";
}

[Route("/test")]
public class TestController : ControllerBase
{
    [HttpGet]
    [Route("jsonTest")]
    public TestObj Test()
    {
        return new TestObj();
    }
}

[Route("/test2")]
public class TestController2 : Controller
{
    [HttpGet]
    [Route("jsonTest")]
    public TestObj Test()
    {
        return new TestObj();
    }
}

[Route("/test3")]
[ApiController]
public class TestController3 : Controller
{
    [HttpGet]
    [Route("jsonTest")]
    public TestObj Test()
    {
        return new TestObj();
    }
}


Solution 1:[1]

If you want to use JsonSerializer.Serialize in action,try to set IgnoreNullValues in JsonSerializerOptions when using it:

var jsonString = System.Text.Json.JsonSerializer.Serialize(new TestObj(), new JsonSerializerOptions{IgnoreNullValues = true,});

result: enter image description here

If you want to return data without null value in the action,you can use:

services.AddControllersWithViews()
            .AddJsonOptions(j =>
            {
                j.JsonSerializerOptions.IgnoreNullValues = true;
            });

action:

public IActionResult Index1([FromBody] TestObj t)
        {
            return Ok(t);
        }

result: enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1