How to return Json instead of XML in ASP.NET Web API ?

Published on December 25, 2016 by admin

Filed under WebAPI

Last modified April 5, 2018

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 2.1 (7 votes)

This article have been viewed 23473 times

When you make a call to the ASP.NET Web API action method and notice this in Google Chrome browser , you would see that by default the data would be displayed in the XML format as shown in the screenshot.


How to return Json instead of XML in ASP.NET Web API ?

You can easily change this behavior by adding the following code in the WebAPIConfig.cs file.

    .Add(new MediaTypeHeaderValue("text/html") );

This will ensure that you would get the Json on the quries unless you explicitly specify the text/xml as the Accept header.


Here’s the WebAPIConfig class file to get this to work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
using System.Net.Http.Headers;

namespace WebApplication1
    public static class WebApiConfig
        public static void Register(HttpConfiguration config)
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));


Leave a Comment


You might be Interested in these Posts

How to read connection string from web.config in ASP.NET and C# ?

Here's a sample code snippet demonstrating how to get the connection string from your ASP.NET

How to Add Web API to existing ASP.NET Web Forms Project ?

In one of the previous posts , we saw how to add the WebAPI to the existing ASP.NET MVC project. Wel...

How to Add Web API to existing ASP.NET MVC Project ?

There are times when you might want to add Web API project to one of your existing ASP.NET MVC proje...