You can change default behaviour of response getting from Web API from XML type to JSON type by removing xml media type from XmlFormatter in Web API configuration.
The problem is to change default behaviour of response returning from Web API as a result from XML type to JSON type.
By default response comes in XML format. You can change default behaviour of response getting from Web API to JSON format. Let's see how to do this with a simple example.
Create a Web API Project. You will find ValuesController inherited from ApiController Add a Get(int id) method and run the application. Execute url api/values/5.
public class ValuesController : ApiController
{
// GET api/values/5
public string Get(int id)
{
return "value:" + id;
}
}
You will see an XML response on browser.
Add lines in WebApiConfig file to remove XML formatter from media type and you will see API response coming in JSON Format.
//This will totally remove xml media type from formatter.
var xmlMediaType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(x => x.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(xmlMediaType);
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//This will totally remove xml media type from formatter.
var xmlMediaType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(x => x.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(xmlMediaType);
}
}
Use this if you want to totally remove XML format as API outcome.
Hope this can help you.