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