5

I'm trying to send a get request to ASP.NET Web API and get back a XML to parse it in my Android app. it returns XML when I try the link via web browser, but it return JSON when Android app send the request. how to fix it in a way it only sends XML? thanks

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
ePezhman
  • 4,010
  • 7
  • 44
  • 80
  • Probably duplicated http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome – Denis Agarev May 23 '13 at 12:15

3 Answers3

5

You could remove the JSON formatter if you don't intend to serve JSON:

var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.JsonFormatter);

You also have the possibility to explicitly specify the formatter to be used in your action:

public object Get()
{
    var model = new 
    {
        Foo = "bar"
    };

    return Request.CreateResponse(HttpStatusCode.OK, model, Configuration.Formatters.XmlFormatter);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Changing the formatters collection is probably the best way, but I would be tempted to clear the collection and add back an XmlFormatter. – Darrel Miller May 23 '13 at 12:41
3

You could also force the accept header on all requests to be application/xml by using a MessageHandler

public class ForceXmlHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        request.Headers.Accept.Clear();
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
        return base.SendAsync(request, cancellationToken);
    }
}

Just add this message handler to the configuration object.

config.MessageHandlers.Add(new ForceXmlHandler());
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
1

You can remove JSON formatter them in Application_Start

Use

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);

Satpal
  • 132,252
  • 13
  • 159
  • 168