Mariusz Jamro
Mariusz Jamro

Reputation: 31673

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

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"
}

Upvotes: 39

Views: 32402

Answers (6)

anaotha
anaotha

Reputation: 623

IN .NET 7, if you want to return indented JSON output and you are using controllers, you can use this in your startup code:

builder.Services.AddControllers()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.WriteIndented = true;
            });

This is using the built in JSON capabilities in .NET, not using any external frameworks like Newtonsoft.

Upvotes: 0

Didar_Uranov
Didar_Uranov

Reputation: 1240

If you want this option only for specific action, using System.Text.Json

return new JsonResult(myResponseObject) { SerializerSettings = new JsonSerializerOptions() { WriteIndented = true } };

Upvotes: 0

Maxuel Rodrigues
Maxuel Rodrigues

Reputation: 19

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;
                });
    }

Upvotes: 1

DavidG
DavidG

Reputation: 119096

.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.

Upvotes: 83

TResponse
TResponse

Reputation: 4125

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

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

Upvotes: 10

Bryan Bedard
Bryan Bedard

Reputation: 2659

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 } };

Upvotes: 18

Related Questions