Home > database >  CamelCaseNamingStrategy not respected for complex type, [FromBody] not working
CamelCaseNamingStrategy not respected for complex type, [FromBody] not working

Time:08-20

Setting up the context first, using an example similar to my actual code. My model is as follows:

public sealed class MyModel
{
    public string Name {get; set;}
    public MyIdentities Id {get; set;}
}

The api is as follows:

[ODataRoute(SomeRoute)]
public async Task<IActionResult> PatchAsync([FromBody] MyModel mod)
{
   // Some Code
}

In startup.cs I have CamelCaseNamingStrategy defined as follows:

 services.AddControllers().AddNewtonsoftJson(options =>
{
     var contractResolver = new CamelCasePropertyNamesContractResolver()
     {
          NamingStrategy = new CamelCaseNamingStrategy(),
      };

      options.SerializerSettings.ContractResolver = contractResolver;
      options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
});

Now when I'm trying to hit the api from postman, using the below request body- the object "mod" is coming as null, even though ModelState is valid.

{
   "Id":{}
}

The object "mod" is NOT null with the below request body:

{
   "id":{}
}

Basically [FromBody] is not parsing the body in the first case. Could someone please explain me why?

CodePudding user response:

I am using

  options.SerializerSettings.ContractResolver =
        new CamelCasePropertyNamesContractResolver();
    options.SerializerSettings.Formatting = Formatting.Indented;

CodePudding user response:

Try this method in startup as well:

        services.AddMvc().AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new 
             CamelCasePropertyNamesContractResolver();

        });
  • Related