NewtonSoft JSON not raising Exception when using MissingMemberHandling.Error

607 views Asked by At

We use the Newtonsoft Json converter to deserialise API requests. As we don't want to receive data/members which are not part of the request class in the BackEnd, we set SerializerSettings.MissingMemberHandling to MissingMemberHandling.Error:

services.AddControllers().AddNewtonsoftJson(a =>
    {
        a.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
    }

But instead of receiving an Exception, we end up with a 'null' request object for the API-call: enter image description here

Why don't we get an Exception?

2

There are 2 answers

0
R. Hoek On BEST ANSWER

I found the problem: my controller was configurered like this:

[Route("api/[controller]")]
public class MyController
{
}

Since everything was working as expected before we added the missing member setting, I did not think of the missing attribute [ApiController]. Adding this, made this controller act like the others regarding the Json serialisation!

[Route("api/[controller]")]
[ApiController]  // <- added this
public class MyController
{
}

To be sure this isn’t forgotten, we wrote a test which checks all controller classes for this attribute.

3
Karney. On

I don't know how you configured Newtonsoft.Json. I make a working example. Here is the steps.

  1. Add the following Nuget package.

    Microsoft.AspNetCore.Mvc.NewtonsoftJson

  2. Configure it in Startup.cs.

     public void ConfigureServices(IServiceCollection services)
     {
         services.AddControllersWithViews()
             .AddNewtonsoftJson(option=>
             {
                 option.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
             });
     }
    
  3. Add a request action and the model. This is the all controller code.

    [ApiController]
    [Route("[controller]")]
    public class ValController:Controller
    {
     [AllowAnonymous]
     [HttpPost]
     public IActionResult LoginAsync([FromBody]Login login)
     {
         return Ok(login);
     }
    }
    public class Login
    {
     public string comm { get; set; }
    }
    
  4. Then I access the action.

enter image description here