我正在开发基于ASP.NET Core Web API的REST服务,并希望在我的端点添加一个参数'prettify',以便响应json将使用缩进格式化并在Web浏览器中可读。
我的问题 - 如何在ASP.WEB API Core应用程序中为每个控制器方法更改JSON格式?
感谢您的帮助。
答案 0 :(得分:2)
感谢@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));
}
}
答案 1 :(得分:1)
创建一个操作过滤器,可用于要添加该功能的操作。我使用DelegatingHandler
在Asp.Net Web API 2(非核心)中实现了相同的功能,它将检查请求并根据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;
}
}
在安装过程中添加为全局消息处理程序。
相同的概念可以应用于动作过滤器。