Thursday, 18 February 2016

How to get result from ASP.NET Web API in either JSON or XML Format?

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?

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

How To Pass An Array As A Parameter While Calling an ASP.NET Web API C#

Please visit my C# Corner Blog for this, where I have provided better efforts to make this concept more understandable - www.c-sharpcorner....