36
votes

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"
}
4
There is usually a "prettify" button in browser which will make JSON readable. Fiddler also have a special tab fro JSON.Alex Sikilinda

4 Answers

78
votes

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

17
votes

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

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

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

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