Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i configure JSON format indents in ASP.NET Core Web API

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" } 
like image 411
Mariusz Jamro Avatar asked Aug 23 '16 11:08

Mariusz Jamro


People also ask

What is the default data format in asp net core Web API?

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.

What is the default format of data response from the Web API service?

By default Web API returns result in XML format.

How do I return JSON in Web API net core?

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 .


2 Answers

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

like image 181
DavidG Avatar answered Sep 28 '22 10:09

DavidG


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 } }; 
like image 27
Bryan Bedard Avatar answered Sep 28 '22 10:09

Bryan Bedard