Wednesday, 14 September 2016

How do i get ASP.Net Web API to return JSON

In my earlier blog, we have seen How to create a Web API? In this blog, we will see about how to return JSON data instead of XML in Web API.
ASP.Net Web API returns XML by default. But we can change so that it should return JSON instead of XML.

To do this open "WebApiConfig.cs" file and add below line :

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"))

Please look at below code sample:

public static void Register(HttpConfiguration config)



                name: "GetDataByID",

                routeTemplate: "api/ad/GetDataByID/{id}",

                defaults: new { Controller = "Test", Action = " GetDataByID " }

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));


Now your Web API will return JSON instead of XML.

Prev Blog - How to create ASP.Net Web API
Next Blog - How to create a secure Web API

Keep following SharePointCafe.Net

No comments:

Post a Comment

Dear Readers, Please post your valuable feedback in the comment section if you like this blog or if you have any suggestions. I would love to hear the same from you. Thanks