【问题标题】:Asp WebApi: Prettify ActionResult JSON outputAsp WebApi:美化 ActionResult JSON 输出
【发布时间】:2017-01-31 21:42:13
【问题描述】:

我正在开发基于 ASP.NET Core Web API 的 REST 服务,并希望向我的端点添加一个参数“prettify”,以便响应 json 将被格式化为缩进并在 Web 浏览器中可读。

我的问题 - 如何在 ASP.WEB API Core 应用程序中更改每个控制器方法的 JSON 格式?

感谢您的帮助。

【问题讨论】:

  • 创建一个操作过滤器,可用于您要添加该功能的任何操作。我使用委托处理程序在 web api(不是核心)中实现了相同的目标。这将检查请求并根据 URL 中的 prettify=true 查询参数更新 json 格式化程序缩进
  • 感谢您的评论,对您有帮助!

标签: c# json rest asp.net-web-api asp.net-core


【解决方案1】:

感谢@Nkosi 的评论,我找到了解决方案。下面是查找“prettify”参数并在输出 JSON 中添加缩进的操作过滤器的代码。如果省略参数,还会添加缩进。

public class OutputFormatActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        var actionResult = context.Result as ObjectResult;
        if (actionResult == null) return;

        var paramObj = context.HttpContext.Request.Query["prettify"];
        var isPrettify = string.IsNullOrEmpty(paramObj) || bool.Parse(paramObj);

        if (!isPrettify) return;

        var settings = new JsonSerializerSettings { Formatting = Formatting.Indented };

        actionResult.Formatters.Add(new JsonOutputFormatter(settings, ArrayPool<char>.Shared));
    }
}

【讨论】:

    【解决方案2】:

    创建一个操作过滤器,可用于您要添加该功能的任何操作。我在 Asp.Net Web API 2(非核心)中使用DelegatingHandler 实现了相同的功能,它将检查请求并根据 URL 中的prettify=true 查询参数更新 json 格式化程序的缩进

    这是委托处理程序的处理方式

    /// <summary>
    /// Custom handler to allow pretty print json results.
    /// </summary>
    public class PrettyPrintJsonHandler : DelegatingHandler {
        const string prettyPrintConstant = "pretty";
        MediaTypeHeaderValue contentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
        private System.Web.Http.HttpConfiguration httpConfig;
        /// <summary>
        /// Initializes a new instance of the <seealso cref="PrettyPrintJsonHandler"/> class with an HTTP Configuration.
        /// </summary>
        /// <param name="config"></param>
        public PrettyPrintJsonHandler(System.Web.Http.HttpConfiguration config) {
            this.httpConfig = config;
        }
    
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {
            var canPrettyPrint = checkQuery(request.RequestUri.Query);
            var jsonFormatter = httpConfig.Formatters.JsonFormatter;
            jsonFormatter.Indent = canPrettyPrint;
    
            var response = await base.SendAsync(request, cancellationToken);
    
            if (canPrettyPrint && response.Content != null) {
                response.Content.Headers.ContentType = contentType;
            }
    
            return response;
        }
    
        private bool checkQuery(string queryString) {
            var canPrettyPrint = false;
            if (!string.IsNullOrWhiteSpace(queryString)) {
                var prettyPrint = QueryString.Parse(queryString)[prettyPrintConstant];
                canPrettyPrint = !string.IsNullOrWhiteSpace(prettyPrint) && Boolean.TryParse(prettyPrint, out canPrettyPrint) && canPrettyPrint;
            }
            return canPrettyPrint;
        }
    }
    

    在设置过程中作为全局消息处理程序添加。

    同样的概念也可以应用于动作过滤器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 2011-10-29
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      相关资源
      最近更新 更多