Thursday, July 31, 2014

Get ASP.NET Web API to return JSON instead of XML

By default, Web API produces XML but if there is need for JSON, given syntax will do it.

Open WebApiConfig.cs file in solution and add mentioned line in it as shown in example.

public static void Register(HttpConfiguration config)
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

            //To produce JSON format add this line of code
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Kindly provide your valuable comments if you find the post helpful.