在HttpConfiguration实例中处理ASP.NET Web API应用程序中的json漂亮打印参数



我需要在我的ASP.NET Web API应用程序中添加并处理可选的"漂亮"参数。当用户发送"漂亮=真"时,应用程序响应应该看起来像一个带有缩进的可读json。当用户发送"漂亮=false"或根本不发送此参数时,他必须得到不带空格符号的json作为响应。

以下是我所拥有的: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方法中的类似逻辑:

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

如何实施?也许应该换一种方式处理?

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

注意:此筛选器检查每个请求中的漂亮打印。重要的是在默认情况下关闭漂亮的打印功能,仅在请求时启用。

步骤1:定义自定义操作筛选器属性,如下所示。

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

相关内容

  • 没有找到相关文章

最新更新