WebAPI and custom model formatters

Just had this little gotcha:

I needed to do some operations on input parameter to a POST method, so wrote a custom formatter, and added it to a list:

config.Formatters.Add(new MyCustomFormatter());

I’m sure those who have done it already see the problem:) Basically web api has a catch-all formatters, so if you do it like this – your formatter will never be called.

This will work:

config.Formatters.Insert(0, new MyCustomFormatter());

Note that this is valid for cases when you’re changing input model, if you want to modify it in response – the .Add method works.

Leave a Reply

Your email address will not be published. Required fields are marked *