Skip to content Skip to sidebar Skip to footer

Web Api 2.0 Recieve Json Data In Camel-case With A Pascal-case Model

I am attempting to make a PUT call to my Web API. I have set the following up in the WebApiConfig.cs to handle sending data back to my Web project in camel case. config.Formatters.

Solution 1:

services
    .AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver
            = newNewtonsoft.Json.Serialization.DefaultContractResolver();
    });

Add this to your Startup.cs if you are in .Net Core project and it will keep the same as .Net class library.

Solution 2:

it looks like you are missing the contentType: "application/json" in your ajax call. In order for Web API to properly handle content negotiation and model binding it has to know what content type is being passed. Without telling the Web API what the content type is it is unable to map the content to the model thus showing it as null on the Action. Below is your snippet updated:

$.ajax({
    url: getApiUrl() + "/roleLocationSecurable",
    type: 'PUT',
    headers: {
        'Authorization': 'Bearer ' + getJwtToken(),
        'LocationId': getCurrentLocation()
    },
    data: dataItem,
    dataType: "json",
   **contentType: "application/json"**
})...

I was able to test this and I see a populated model.

Solution 3:

Have you tried to annotate your model attributes with a JsonProperty. For example this:

[JsonProperty("Id")]
publicint? Id {get;set;}

[JsonProperty("RoleLocationId ")]
publicint RoleLocationId {get;set;}

[JsonProperty("ModuleId ")]
publicint ModuleId {get;set;}

Remember to invoke this assembly: using Newtonsoft.Json;

Post a Comment for "Web Api 2.0 Recieve Json Data In Camel-case With A Pascal-case Model"