Handling json pretty print param in ASP.NET Web API application in HttpConfiguration instance

淺唱寂寞╮ 提交于 2019-12-24 04:43:05

问题


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?


回答1:


Motivation: Pretty print if the query string contains the word prettyprint or prettyprint=true, don't pretty print if the there's no word prettyprint in the query string or prettyprint=false.

Note: This filter checks for pretty print in every request. It is important to turn off the pretty print feature by default, enable only if request.

Step 1: Define a Custom action filter attribute as below.

public class PrettyPrintFilterAttribute : ActionFilterAttribute
{
    /// <summary>
    /// Constant for the query string key word
    /// </summary>
    const string prettyPrintConstant = "prettyprint";

    /// <summary>
    /// Interceptor that parses the query string and pretty prints 
    /// </summary>
    /// <param name="actionExecutedContext"></param>
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {            
        JsonMediaTypeFormatter jsonFormatter = actionExecutedContext.ActionContext.RequestContext.Configuration.Formatters.JsonFormatter;
        jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;

        var queryString = actionExecutedContext.ActionContext.Request.RequestUri.Query;
        if (!String.IsNullOrWhiteSpace(queryString))
        {
            string prettyPrint = HttpUtility.ParseQueryString(queryString.ToLower().Substring(1))[prettyPrintConstant];
            bool canPrettyPrint;
            if ((string.IsNullOrEmpty(prettyPrint) && queryString.ToLower().Contains(prettyPrintConstant)) ||
                Boolean.TryParse(prettyPrint, out canPrettyPrint) && canPrettyPrint)
            {                    
                jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
            }
        }
        base.OnActionExecuted(actionExecutedContext);
    }
}

Step 2: Configure this filter globally.

public static void Register(HttpConfiguration config)
    {            
        config.Filters.Add(new PrettyPrintFilterAttribute());       
    }


来源:https://stackoverflow.com/questions/29289185/handling-json-pretty-print-param-in-asp-net-web-api-application-in-httpconfigura

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!