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

4

3 回答 3

5

如果您不打算提供 JSON,则可以删除 JSON 格式化程序:

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

您还可以明确指定要在您的操作中使用的格式化程序:

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

    return Request.CreateResponse(HttpStatusCode.OK, model, Configuration.Formatters.XmlFormatter);
}
于 2013-05-23T12:15:39.793 回答
3

application/xml您还可以使用 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);
    }
}

只需将此消息处理程序添加到配置对象即可。

config.MessageHandlers.Add(new ForceXmlHandler());
于 2013-05-23T12:40:09.950 回答
1

您可以在其中删除 JSON 格式化程序Application_Start

利用

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

于 2013-05-23T12:41:17.713 回答