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) {
-
-
- config.Formatters.Clear();
- config.Formatters.Add(new JsonMediaTypeFormatter());
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {
- id = RouteParameter.Optional
- });
- }