You can get JsonOutputFormatter from BindingContext.OutputFormatters inside your controller code. This allows you to dynamically change SerializerSettings .
Try enabling using Newtonsoft.Json; into the controller code and do the following inside your controller action:
var f = BindingContext.OutputFormatters.FirstOrDefault( formatter => formatter.GetType() == typeof (Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter)) as Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter; if (f != null) {
I turned on Formatting = Formatting.Indented only for my tests, because you immediately see the results. You do not need it.
UPDATED: I created a demo project using an MVC web application without authentication. Then I added the following method to HomeController
public object TestMethod() { var testResult = new { name = "Test", value = 123, nullableProperty = (string) null }; return testResult; }
and changed the project start URL to Home/TestMethod and started the demo. I could see
{"name":"Test","value":123,"nullableProperty":null}
You do not need to add any additional use statements to use the code that I published at the beginning (you just need to have standard ones using Microsoft.AspNet.Mvc; and using System.Linq; ), but the code can be more readable if you had would using Microsoft.AspNet.Mvc.Formatters; and using Newtonsoft.Json; . I added using statements for Microsoft.AspNet.Mvc.Formatters and Newtonsoft.Json and changed the code to the following
public object TestMethod() { var testResult = new { name = "Test", value = 123, nullableProperty = (string) null }; var f = BindingContext.OutputFormatters.FirstOrDefault( formatter => formatter.GetType() == typeof (JsonOutputFormatter)) as JsonOutputFormatter; if (f != null) { f.SerializerSettings.Formatting = Formatting.Indented; f.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; } return testResult; }
The output results now look like this
{ "name": "Test", "value": 123 }
The standard code uses "Newtonsoft.Json" in version 6.0.6. We can add "Newtonsoft.Json": "8.0.2" depending on the use of the latest version of Newtonsoft.Json . See Problem with resolving indirect dependencies that I reported in the problem and which is still open.
You can download the test project from here .