0

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?

R. Hoek
  • 916
  • 8
  • 27

2 Answers2

1

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

Karney.
  • 4,803
  • 2
  • 7
  • 11
  • This is what I already did - but I digged a bit more into this and it seems the problem only occurs wich one API-controler. One note - that API-controle allows anonymous API-call, while the others don't. But yours here also allows anonymous calls... – R. Hoek Nov 25 '20 at 10:45
  • Yes, I added the `[ApiController]`. This is the all code. – Karney. Nov 26 '20 at 01:03
  • Thanks Karney. I’ve upvoted your post as it gives a nice full source and full functionality demo of what I was aspecting, but the actual problem lies in the fact of the missing [ApiController] attribute. So therefor I’ll be checking my own answer as the actual answer to my question. – R. Hoek Nov 26 '20 at 06:33
0

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.

R. Hoek
  • 916
  • 8
  • 27