4
votes

We are using WebAPI to mimic the handling of a legacy system. As a result, we would like the default response formatter to be the XmlFormatter and not the JsonFormatter. The reason is that some of the existing calls to the service do not supply the Accept: HTTP header field.

I can achieve this by removing the JsonFormatter from the Formatters collection and then re-adding it, forcing it to be at the end of the chain.

This then result in the default format response using the XmlFormatter. Although it works, it just doesn't feel correct, and although I am moving Json to the back of the collection, there is no guarantee that the XmlFormatter is at the front of the collection.

Ideas/thoughts?

2

2 Answers

11
votes

Just add formatters in the right order. If ASP.NET Web API finds two formatters for the same content type, it will pick the first one, so it is very important to add formatters in the right order.

//somewhere in Web Api config
config.Formatters.Clear();
config.Formatters.Add(new XmlMediaTypeFormatter());
config.Formatters.Add(new JsonMediaTypeFormatter());

So the default will be XML, the first formatter, but the API still supports JSON if the request asks for it (with appropriate HTTP header).

Finally, another different approach, is to use a custom IContentNegotiator. It will allow you to select the most appropriate MediaTypeFormatter for a given request.

//somewhere in Web Api config
config.Services.Replace(typeof(IContentNegotiator), new MyCustomContentNegotiator());

An example is available here.

0
votes

This is returned to automatically serialise and return json when content type is json.

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;