Tuesday, May 31, 2016

Web API to return JSON instead of XML

Web API to return JSON instead of XML

Concert crowd

Out of the box Web API generates XML as a result however if there is need for JSON as response than a little change may help you as given below:


Kinly open WebApiConfig.cs file add the following code segment depicted below in red:

public static void Register(HttpConfiguration config)
      {
          config.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector((config)));
                    
          config.Routes.MapHttpRoute(
              name: "Version1",
              routeTemplate: "api/v1/{controller}/{action}/{id}",
              defaults: new { controller = "Employees", Action = "FetchEmployeeById", id = RouteParameter.Optional }
          );

//To produce JSON format add this line of code

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(newMediaTypeHeaderValue("text/html"));

}

Hope it will help you.

Learn more about MVC and WebApi :

http://www.dotnetpiper.com/search/label/MVC

http://www.dotnetpiper.com/search/label/WCF%20and%20WebAPI

0 comments :

Post a Comment