I need specific JSON settings per controller in my ASP.NET MVC 6 webApi. I found this sample that works (I hope !) for MVC 5 : Force CamelCase on ASP.NET WebAPI Per Control
You can use a return type of JsonResult on your controller action methods. In my case, I needed specific actions to return Pascal Case for certain legacy scenarios. The JsonResult object allows you to pass an optional parameter as the JsonSerializerSettings.
public JsonResult Get(string id)
{
var data = _service.getData(id);
return Json(data, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver()
});
}
To have more consistent controller method signatures I ended up creating an extension method:
public static JsonResult ToPascalCase(this Controller controller, object model)
{
return controller.Json(model, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver()
});
}
Now I can simply call the extension method inside my controller like below:
public IActionResult Get(string id)
{
var data = _service.getData(id);
return this.ToPascalCase(data);
}