Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ASP.NET Web API to only return XML?

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

like image 772
ePezhman Avatar asked May 23 '13 12:05

ePezhman


3 Answers

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);
}
like image 96
Darin Dimitrov Avatar answered Sep 23 '22 13:09

Darin Dimitrov


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());
like image 29
Darrel Miller Avatar answered Sep 22 '22 13:09

Darrel Miller


You can remove JSON formatter them in Application_Start

Use

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

like image 23
Satpal Avatar answered Sep 26 '22 13:09

Satpal