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

Published on November 25, 2016 by abundantcode

Filed under WebAPI

Last modified November 25, 2016

Print this page

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

This article have been viewed 403 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"));

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment


You might be Interested in these Posts

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...

How to read a connection string from web.config file in ASP.NET ?

Assume that you have a connectionstring configured in the web.config file of your ASP.NET applicatio...