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)

{

config.Routes.MapHttpRoute(

                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.

You may also like –

Web API Interview Questions and Answers

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

Keep following SharePointCafe.Net

Leave a Comment

RSS
YouTube
YouTube
Instagram