Reputation: 380
In ASP.NET Web API Controllers I'm using JsonResults like this:
return Json(data);
I've set in the WebApiConfig the global defaults as I found in many places suggested.
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
I thought this would be make the settings be used, but it is not. To workaround it I'm calling:
return Json(data, GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings);
This works fine, but am I missing something to make the Global Serialization Settings apply all the time?
Upvotes: 1
Views: 88
Reputation: 1744
By calling Json(data), you are executing this overload - you can see it's creating a new instance of serializer settings
protected internal JsonResult<T> Json<T>(T content)
{
return Json<T>(content, new JsonSerializerSettings());
}
If you use one of ApiController methods that return a negotiated result, such as ApiController.Ok, e.g return Ok(data)
, then the formatters are resolved from the global configuration and you'll see the behaviour you require.
Upvotes: 2