How to configure C# WebApi2 to display data in JSON format directly in browser?[Solved]
Recently I was asked a question “How to configure C# WebApi2 to display data in JSON format directly in browser?” by one of my colleague.
This is a simple solution and some explaination as below.
By default, MVC Web API 2 framework serializes all the return object from an controller action in to XML format and display the same on the browser. To override this, we need to set an “ContentType” Header in every request informing to the framework to provide output in JSON format. If you are requesting from browser sending header is not possible. So, to enable JSON format output directly in browser we need to override the default formatter in WebAPi settings in our application in
App_Start/WebApiConfig.cs class as follows.
config.Formatters.JsonFormatter.SupportedMediaTypes .Add(new MediaTypeHeaderValue("text/html") );
Hope you got some help with this explanation and code base.
Happy Coding 🙂