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

1

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Changing the formatters collection is probably the best way, but I would be tempted to clear the collection and add back an XmlFormatter.
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());

Comments

1

You can remove JSON formatter them in Application_Start

Use

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.