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