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 (GlobalConfiguration.Configuration.Formatters.XmlFormatter == null)
{
GlobalConfiguration.Configuration.Formatters.Add(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
if (GlobalConfiguration.Configuration.Formatters.JsonFormatter == null)
{
GlobalConfiguration.Configuration.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
}
if (id == 1)
{
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
}
else
{
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;
}
return "value";
}
Add the below code
app_start
event inglobal.asax
file. In API Url add the query string:e.g.:
If your request specifies the mime type, for example
application/json
, then web api will format the response appropriately.If you are attempting to debug your web api manually, use a tool like Fiddler 2 to specify the type.
This article describes the concept.
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):
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!).
QueryStringMapping` is nice solution but I need a default value for type.
for xml :
localhost:49533/api/?type=xml
for json:
localhost:49533/api/
I solve that situation like that:
What you are trying to do will not work in a multi-threaded environment. You cannot add to and remove from the formatters collection on a per-request basis. Here is a better way of accomplishing what you want.
Looked into this a bit more, and found your answer in another post: