I try to get the output XML or JSON data based on my input. I used the below WEB API code but not able to exact output.
public string Get(int id)
{
if (G
While the accepted answer by vijayjan15 seems the best way to go for your specific situation (that is, using the MediaTypeMappings), you could alternatively have two different methods, one that returns XML and one that returns JSON. To do that, you can instantiate a controller-specific HttpConfiguration (to avoid modifying the one in GlobalConfiguration.Configuration):
public MyReturnType GetMyTypeAsXml() {
Configuration = new HttpConfiguration();
Configuration.Formatters.Clear();
Configuration.Formatters.Add(new XmlMediaTypeFormatter());
return new MyReturnType();
}
public MyReturnType GetMyTypeAsJson() {
Configuration = new HttpConfiguration();
Configuration.Formatters.Clear();
Configuration.Formatters.Add(new JsonMediaTypeFormatter());
return new MyReturnType();
}
I'm not sure how much overhead there is in spinning up a new instance of HttpConfiguration (I suspect not a lot), but the new instance comes with the Formatters collection filled by default, which is why you have to clear it right after instantiating it. Note that it if you don't use Configuration = new HttpConfiguration(), and instead modify Configuration directly, it modifies the GlobalConfiguration.Configuration property (so, it would impact all your other WebApi methods - bad!).