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"
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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.
Method 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 } };
Method 3
In .NetCore 3+ you can achieve this as follows:
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.WriteIndented = true;
});
Method 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;
});
}
Method 5
If you want this option only for specific action, using System.Text.Json
return new JsonResult(myResponseObject) { SerializerSettings = new JsonSerializerOptions() { WriteIndented = true } };
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0