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

SharePointCafe Admin Avatar
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

Tagged in :

SharePointCafe Admin Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *

RSS
YouTube
YouTube
Instagram