How can i configure JSON format indents in ASP.NET Core Web API
Solution 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.
Solution 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 } };
Solution 3
In .NetCore 3+ you can achieve this as follows:
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.WriteIndented = true;
});
Solution 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;
});
}
Mariusz Jamro
Updated on September 17, 2021Comments
-
Mariusz Jamro over 2 years
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" }
-
Max about 5 yearsNote that
SerializerSettings
is inMicrosoft.AspNetCore.Mvc
, but in order to useFormatting
you need ausing Newtonsoft.Json
. -
user1574598 over 4 yearsThis is what I needed
options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
-
Max about 4 yearsThis is the best answer now. I just submitted a suggested edit to incorporate this into DavidG's accepted answer.
-
BrainSlugs83 about 3 yearsIn 2.x we used to add a MediaTypeMapping for Json to be "application/json" (otherwise the browser would ignore the formatting). How do we add a similar mapping in 3.0 and higher?