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" }
By default, ASP.NET Core supports application/json , text/json , and text/plain media types. Tools such as Fiddler or Postman can set the Accept request header to specify the return format.
By default Web API returns result in XML format.
To return data in a specific format from a controller that inherits from the Controller base class, use the built-in helper method Json to return JSON and Content for plain text. Your action method should return either the specific result type (for instance, JsonResult ) or IActionResult .
.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.
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 } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With