Anupheaus
Anupheaus

Reputation: 3811

Camel Case Web API Json settings do not seem to be working

I have this code in my WebApiConfig.cs file and within the Register method:

var jsonFormatter=config.Formatters.JsonFormatter;
jsonFormatter.UseDataContractJsonSerializer = false;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

And yet despite this (and I did make sure this code was definitely being executed by using Debugger.Launch()) it is still outputting all my Json in Pascal Case.

Here is the code in the action method:

[HttpGet]
[Route("Details")]
public IHttpActionResult Details() {            
    using (var context = new Security.Context()) {              
        var user = context.Users.Current;
        if (user == null) { return Json((object)null); }
        return Json(user);
    }
}

I can't see what I'm doing wrong, is there something I am missing?

Upvotes: 2

Views: 1904

Answers (2)

Sergey Kolodiy
Sergey Kolodiy

Reputation: 5909

Instead of returning IHttpActionResult, return the concrete type (User in your case). This way, you'll avoid lots of potential issues, including serialization, testability, and content negotiation as well.

Upvotes: 1

Anupheaus
Anupheaus

Reputation: 3811

So maybe someone can explain this but I found out that using the ApiController.Json method does not appear to use any of the global formatters (I removed them all and this method still functioned and returned valid Json albeit in Pascal Case).

When I use the ApiController.Ok method, this does use the global formatters and any settings applied to them, like the CamelCasePropertyNamesContractResolver.

So my solution is to use "Ok" instead of "Json"...but why they are different I don't know...

Upvotes: 1

Related Questions