Wednesday, 14 September 2016

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.

No comments:

Post a Comment