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 を返します。
まだ見えない解決策はありますか?