使用 ASP.NET Core 3 和 System.Text.Json,您可以通过添加返回格式精美的 JSON
services.AddControllers().AddJsonOptions(
options => options.JsonSerializerOptions.WriteIndented = true);
到您的 Startup.cs ...
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddApiVersioning(o =>
{
o.AssumeDefaultVersionWhenUnspecified = true;
o.DefaultApiVersion = new ApiVersion(1, 0);
});
services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
}
...但这意味着,它可以为所有端点全局打印所有 JSON 输出。
有没有办法在端点级别决定漂亮与否,例如通过查询字符串“pretty=true”?:
https://localhost:5001/api/v1/persons/1231221.json?pretty=true
在你的 Controllers/PersonController.cs 你可以做......
[HttpGet]
[Route("/api/v{version:apiVersion}/[controller]/{id}.json")]
public IActionResult PersonAsJson([FromRoute] int id, [FromQuery] bool pretty = false)
{
var person = new Person(id)
// ...
if (pretty)
{
Response.Headers.Add("Content-Type", "text/plain");
return Ok(JsonSerializer.Serialize(
person,
new JsonSerializerOptions { WriteIndented = true }));
}
// non pretty output if there's no
// services.AddControllers().AddJsonOptions(
// options => options.JsonSerializerOptions.WriteIndented = true);
// in Startup.cs
Response.Headers.Add("Content-Type", "application/json");
return Ok(person);
}
...但这显然会为格式精美的 JSON 返回错误的 Content-Type。
我还看不到的任何解决方案?