In this article I am going to explain how to return data in JSON
format from ASP.NET Web API.
In previous article I have explained how to create First WebAPI Hello World application with repository pattern, how to create Web APIfirst Hello world application and Introduction To ASP.NET Web API.
As you know ASP.NET Web API by default return the data in XML
format when we run the API in browsers. Here, we are going to learn to change
the return data/response to JSON.
You can achieve this from WebApiConfig.cs
file. You can find this file under App_Start
folder. Firstly, add the namespace to config file
using System.Net.Http.Headers;
and add the below given
code in this file:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Complete
code of WebApiConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
using Unity;
using WEBAPI.Models;
using WEBAPI.Interface;
using WEBAPI.Services;
namespace WEBAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web
API reutrn Json data
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
//
Web API routes
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
If you want return data in both XML and JSON format, then you
need to pass querystring parameter.
Complete
code of WebApiConfig.cs to return data in both JSON &XML
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
using Unity;
using WEBAPI.Models;
using WEBAPI.Interface;
using WEBAPI.Services;
namespace WEBAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web
API reutrn both Json & XML data
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "xml", new MediaTypeHeaderValue("application/xml")));
// Web
API routes
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
No comments:
Post a Comment