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).
- $.ajax({
- url: 'http://localhost:11129/api/values',
- type: 'GET',
- dataType: 'xml',
- ContentType: "application/rss+xml",
- success: function(data, textStatus, xhr) {
- console.log(data);
- },
- error: function(xhr, textStatus, errorThrown) {
- console.log('a' + textStatus);
- }
- }).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());
- public static void Register(HttpConfiguration config) {
- // Web API configuration and services
- // Web API routes
- config.Formatters.Clear();
- config.Formatters.Add(new JsonMediaTypeFormatter());
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {
- id = RouteParameter.Optional
- });
- }
ravi kumarPosted Aug 17, 2019, 1:07 AM
Online Json Viewer and Formatter helps to format the json structure, validate json and to view the structure in Treeview format. Visit link http://jsonviewerandformatter.freeasphost.net
Manav PandyaPosted Sep 26, 2017, 9:54 AM
Nice share ....................
Satyaprakash SamantarayPosted May 10, 2017, 7:02 AM
Where is the ouput ????
Saravanakumar SekaranPosted May 10, 2017, 3:04 AM
Wow nice one keep sharing