Situation may exist some time as we want the data from API in JSON or either in XML format. So how to achieve that in ASP.NET Web API?
For JSON :
For XML :
Now use query string while calling the API.
as ::
Here is the solution:
Add Namespace:
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
Go to -> Global.asax file and Add following script to Application_Start().
For JSON :
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
For XML :
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
Now use query string while calling the API.
as ::
for xml : http://localhost:49533/api/?type=xml
for json: http://localhost:49533/api/?type=json
That's it this is how we can get data as we want in XML or JSON.
No comments:
Post a Comment