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.

  1. public static void Register(HttpConfiguration config)   
  2. {  
  3.     config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new   
  4.     {  
  5.         id = RouteParameter.Optional  
  6.     });  
  7.     //To produce JSON format add this line of code  
  8.     config.Formatters.JsonFormatter.SupportedMediaTypes.Add(newMediaTypeHeaderValue("text/html"));  
  9. }  
Kindly provide your valuable comments if you find the post helpful.
Ebook Download
View all
Learn
View all