Click here to Skip to main content
15,301,841 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi I got an output in web Api result as below instead of json

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ArrayOfstring xmlns:i="" xmlns="">

My Controller:

public class ValuesController : ApiController
       public IHttpActionResult Get()
           return Ok(new[]{"X","Y"});

WebConfig.cs :

public static void Register(HttpConfiguration config)
            // Web API configuration and services

            // Web API routes

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

I expect json output {"X","Y"} but it produces above result output
F-ES Sitecore 19-Aug-15 16:22pm
You'll get this when requesting the url via the browser as the browser specifies it wants html back. When you call it via code and the code specifies it wants json back then the service will return the json you're expecting.
sreeyush sudhakaran 20-Aug-15 0:08am
Sorry it is actually a sample program got from MVA they are getting output in browser itself

1 solution

Web API, by default returns XML and JSON. You can override the behavior to always return a preferred result. Either by adding a header, or by changing the Web API setting.

One easy way to do this is to remove the XML support in the configuration itself,

   new MediaTypeHeaderValue("text/html") 

Another way that I talked about was to add "Content-Type" header and set the value to "application/json". Or when you add a header (this header goes with the Request, typically with the HttpClient itself) of "Accept" and set it to "application/json".

Personally saying, Web API always returns JSON format content in my case. I have never stumbled upon a case where I get to have the XML data.

Here are the helpful threads from internet:[^][^][^]

If you are using jQuery to get the data, you should always consider using $.getJSON() function. It does all of the header settings for you itself. :-)
sreeyush sudhakaran 20-Aug-15 0:10am
Sorry it is actually a sample program got from MVA they are getting JSON output in browser itself without any modification of code , What may be the reason , any way I will workout your solution and get back to you , Iam very new to Web API also :)
Afzaal Ahmad Zeeshan 20-Aug-15 5:47am
Yes, they do. In my case mostly I get JSON but in some cases (when debugging on my mobile) I get XML. But that doesn't matter, because I rarely use mobile phones!

Please use the code that I have provided.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900