Reputation: 31673
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"
}
Upvotes: 39
Views: 32402
Reputation: 623
IN .NET 7, if you want to return indented JSON output and you are using controllers, you can use this in your startup code:
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.WriteIndented = true;
});
This is using the built in JSON capabilities in .NET, not using any external frameworks like Newtonsoft.
Upvotes: 0
Reputation: 1240
If you want this option only for specific action, using System.Text.Json
return new JsonResult(myResponseObject) { SerializerSettings = new JsonSerializerOptions() { WriteIndented = true } };
Upvotes: 0
Reputation: 19
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;
});
}
Upvotes: 1
Reputation: 119096
.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.
Upvotes: 83
Reputation: 4125
In .NetCore 3+ you can achieve this as follows:
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.WriteIndented = true;
});
Upvotes: 10
Reputation: 2659
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 } };
Upvotes: 18