Web API: Configure JSON serializer settings on action or controller level
Option 1 (quickest)
At action level you may always use a custom JsonSerializerSettings
instance while using Json
method:
public class MyController : ApiController
{
public IHttpActionResult Get()
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var model = new MyModel();
return Json(model, settings);
}
}
Option 2 (controller level)
You may create a new IControllerConfiguration
attribute which customizes the JsonFormatter:
public class CustomJsonAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
var formatter = controllerSettings.Formatters.JsonFormatter;
controllerSettings.Formatters.Remove(formatter);
formatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
};
controllerSettings.Formatters.Insert(0, formatter);
}
}
[CustomJson]
public class MyController : ApiController
{
public IHttpActionResult Get()
{
var model = new MyModel();
return Ok(model);
}
}
Here's an implementation of the above as Action Attribute:
public class CustomActionJsonFormatAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext?.Response == null) return;
var content = actionExecutedContext.Response.Content as ObjectContent;
if (content?.Formatter is JsonMediaTypeFormatter)
{
var formatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
};
actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, formatter);
}
}
}
public class MyController : ApiController
{
[CustomActionJsonFormat]
public IHttpActionResult Get()
{
var model = new MyModel();
return Ok(model);
}
}