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

I am trying to send a request for an ASP.NET Web API and return the XML for parsing it in an Android application. it returns XML when I try to use a link through a web browser, but returns JSON when an Android application sends a request. How to fix it as soon as it sends XML? thanks

+4
source share
3 answers

You can remove the JSON formatter if you are not going to use JSON:

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

You also have the option 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); } 
+5
source

You can also force the accept header for all application/xml requests to use 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()); 
+2
source

You can remove the JSON formatter in Application_Start

Using

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

+1
source

Source: https://habr.com/ru/post/1482377/


All Articles