I need to add and handle optional "pretty" parameter in my ASP.NET Web API application. When user sends "pretty=true", the application response should look like a human-readable json with indentations. When user sends "pretty=false" or does not send this parameter at all, he must get json with no space symbols in response.
Here's 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 the logic like this in Register method:
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 it can be implemented? Maybe it should be handled some other way?