I need to add and process the optional "pretty" parameter in an ASP.NET Web API application. When the user sends "pretty = true", the application response should look like human-readable json with indentations. When the user sends "pretty = false" or does not send this parameter at all, he should receive json without spaces in the answer.
Here is what I have:
Global.asax.cs
public class WebApiApplication
: HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ValidateModelAttribute());
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Newtonsoft.Json.Formatting.Indented
};
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
...
As you understand, I need logic in this method. Registration :
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Newtonsoft.Json.Formatting.Indented
};
if(prettyPrint) // must be extracted from request and passed here somehow
{
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
}
How can this be implemented? Maybe this should be handled in some other way?