using System.Text.JSON with ASP.NET Core 3: decide about pretty JSON output on endpoint?

Viewed 1324

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?

2 Answers

Since both of your responses must satisfy Content-Type: application/json, I would do it this way:

[HttpGet]
[Route("/api/v{version:apiVersion}/[controller]/{id}.json")]
public IActionResult PersonAsJson([FromRoute] int id, [FromQuery] bool pretty = false)
{
    var person = new Person(id)

    // ...

    Response.Headers.Add("Content-Type", "application/json");

    if (pretty)
    {
        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

    return Ok(person);
}

No need to set headers twice.

It can be the type of content:

    Response.Headers.Add("Content-Type", "application/json;");

would be like :

if (pretty)
{
    Response.Headers.Add("Content-Type", "application/json;");

    return Ok(JsonSerializer.Serialize(
        person,
        new JsonSerializerOptions { WriteIndented = true }));
}
Related