How can i configure JSON format indents in ASP.NET Core Web API

26,300

Solution 1

.NET Core 2.2 and lower:

In your Startup.cs file, call the AddJsonOptions extension:

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.Formatting = Formatting.Indented;
    });

Note that this solution requires Newtonsoft.Json.

.NET Core 3.0 and higher:

In your Startup.cs file, call the AddJsonOptions extension:

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.WriteIndented = true;
    });

As for switching the option based on environment, this answer should help.

Solution 2

If you want to turn on this option for a single controller instead of for all JSON, you can have your controller return a JsonResult and pass the Formatting.Indented when constructing the JsonResult like this:

return new JsonResult(myResponseObject) { SerializerSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented } };

Solution 3

In .NetCore 3+ you can achieve this as follows:

services.AddMvc()
    .AddJsonOptions(options =>
    {               
         options.JsonSerializerOptions.WriteIndented = true;    
    });

Solution 4

In my project, I used Microsoft.AspNetCore.Mvc with the code below for all controllers. This for .NET Core 3.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.Formatting = Formatting.Indented;
                });
    }
Share:
26,300
Mariusz Jamro
Author by

Mariusz Jamro

Updated on September 17, 2021

Comments

  • Mariusz Jamro
    Mariusz Jamro over 2 years

    How can i configure ASP.NET Core Web Api controller to return pretty formatted json for Development enviroment only?

    By default it returns something like:

    {"id":1,"code":"4315"}
    

    I would like to have indents in the response for readability:

    {
        "id": 1,
        "code": "4315"
    }
    
  • Max
    Max about 5 years
    Note that SerializerSettings is in Microsoft.AspNetCore.Mvc, but in order to use Formatting you need a using Newtonsoft.Json.
  • user1574598
    user1574598 over 4 years
    This is what I needed options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
  • Max
    Max about 4 years
    This is the best answer now. I just submitted a suggested edit to incorporate this into DavidG's accepted answer.
  • BrainSlugs83
    BrainSlugs83 about 3 years
    In 2.x we used to add a MediaTypeMapping for Json to be "application/json" (otherwise the browser would ignore the formatting). How do we add a similar mapping in 3.0 and higher?