Return Data In JSON Format From Web API

Here, we will learn how to return JSON data from Web API. In Web API, the return type will be decided by the client demand type, as shown below (highlighted in Yellow color). 
  1. $.ajax({  
  2.     url: 'http://localhost:11129/api/values',  
  3.     type: 'GET',  
  4.     dataType: 'xml',  
  5.     ContentType: "application/rss+xml",  
  6.     success: function(data, textStatus, xhr) {  
  7.         console.log(data);  
  8.     },  
  9.     error: function(xhr, textStatus, errorThrown) {  
  10.         console.log('a' + textStatus);  
  11.     }  
  12. }).done(function() {});   
We can make an output as JSON format by default, if the user doesn't provide any data type in the request body, by adding two lines given below in top of the WebApiConfig.cs file in app_start folder.
  • config.Formatters.Clear();
  • config.Formatters.Add(new JsonMediaTypeFormatter()); 
  1. public static void Register(HttpConfiguration config) {  
  2.     // Web API configuration and services  
  3.     // Web API routes  
  4.     config.Formatters.Clear();  
  5.     config.Formatters.Add(new JsonMediaTypeFormatter());  
  6.     config.MapHttpAttributeRoutes();  
  7.     config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {  
  8.         id = RouteParameter.Optional  
  9.     });  
Ebook Download
View all
Learn
View all