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

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(newMediaTypeHeaderValue("text/html"))

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(newMediaTypeHeaderValue("text/html"));

}


Now your web api will return JSON instead of XML.

Comments

Popular posts from this blog

CAML Query in SharePoint 2010

Calling REST APi from server side code - C#

All about SharePoint 2010 Content Type Hub

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX