我需要在ASP.NET Web API应用程序中添加和处理可选的“pretty”参数。 当用户发送“pretty = true”时,应用程序响应应该看起来像带有缩进的人类可读的json。 当用户发送“pretty = 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());
...
如您所知,我需要注册方法中的逻辑:
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;
}
如何实施?也许它应该以其他方式处理?
答案 0 :(得分:5)
动机:如果查询字符串包含单词prettyprint
或prettyprint=true
,则打印得非常漂亮,如果没有单词,请不要打印。查询字符串中的{1}}或prettyprint
。
注意:此过滤器会检查每个请求中的精美打印。默认情况下关闭漂亮的打印功能非常重要,仅在请求时启用。
第1步:定义自定义操作过滤器属性,如下所示。
prettyprint=false
第2步:全局配置此过滤器。
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);
}
}