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


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);
}

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());

You can remove JSON formatter them in Application_Start

Use

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

链接地址: http://www.djcxy.com/p/3468.html

上一篇: 如何将json POST数据作为对象传递给Web API方法?

下一篇: 如何使ASP.NET Web API只返回XML?