Different data type in Web API response of the same method

Both XML and JSON in return result of Web API REST service method

Web API restful services are very flexible and they return different data format (JSON or XML) depending on accept type header value from your browser (or other client).

However this is not always so precise so sometime you have to force return type. More on how to force return type on API method side itself you can find in this article. This is useful if you do not control you request, for example if you have Web API method link exposed on your web page, but in case you initiate request in a back-end with C# or JavaScript read this short article.

As I mentioned at the beginning, response serialization type is based on accept type header value of the client. Based on this we can set this header value to get different value.

As an example I will use generic class and get method which is created when you choose Web API in new project dialog in Visual Studio. After creating new project in Visual Studio with MVC 4 Web API template, Values controller will be created with the following methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MvcTests.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}
    

For testing purposes, I created a small Windows Forms app for testing this behavior. It is attached to this document for downloading with source included.

Webapitestapp

Test app is very simple, one button is going to fetch XML response and other one will fetch JSON result from GET method of the Web API REST service.

        public static string GetXmlResult()
        {
            var request = (HttpWebRequest)WebRequest.Create("http://localhost:6060/api/values");
            request.Method = "GET";
            request.Accept = "text/xml";
            request.Timeout = 500000;

            var response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                return new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
            }

            return null;
        }
    

This method will tel service that is accepts XML and data will be returned as XML. By changing only one line and setting different value for accept header value we will get JSON result.

request.Accept = "text/json";
    

Another way to fetch different data format from Web API service is using JQuery on client side, with the same approach by setting accept header value in a request. Read more about how to do it with JQuery here.

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article