本文介绍了在HttpConfiguration实例中的ASP.NET Web API应用程序中处理JSON漂亮打印参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在ASP.NET Web API应用程序中添加并处理可选的"pretty"参数.当用户发送"pretty = true"时,应用程序响应应类似于带有缩进的人类可读json.当用户发送"pretty = false"或根本不发送此参数时,他必须获取没有空格符号的json作为响应.

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.

这是我所拥有的: 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());
...

如您所知,在 Register 方法中,我需要这样的逻辑:

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?

推荐答案

动机:如果查询字符串包含单词prettyprintprettyprint=true,则漂亮打印;如果查询字符串中包含单词prettyprintprettyprint=true,则漂亮打印.查询字符串或prettyprint=false中没有单词prettyprint.

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.

步骤1:如下定义自定义操作"过滤器属性.

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);
    }
}

步骤2:全局配置此过滤器.

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

这篇关于在HttpConfiguration实例中的ASP.NET Web API应用程序中处理JSON漂亮打印参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 22:47