Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default WebAPI formatter

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?

like image 963
Carl Clark Avatar asked Dec 14 '22 22:12

Carl Clark


1 Answers

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.

like image 174
Cybermaxs Avatar answered Mar 15 '23 07:03

Cybermaxs