With ASP.NET Core 3 and System.Text.Json you can return pretty formatted JSON by adding
services.AddControllers().AddJsonOptions(
options => options.JsonSerializerOptions.WriteIndented = true);
to your 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);
}
... but this means, it's pretty printing all JSON output globally for all endpoints.
Is there a way to decide about pretty or not on endpoint level, e. g. by query string "pretty=true"?:
https://localhost:5001/api/v1/persons/1231221.json?pretty=true
In your Controllers/PersonController.cs you could do ...
[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);
}
... but this obviously returns the wrong Content-Type for pretty formatted JSON.
Any solution for that I yet can't see?