in

ASP.NET Weblogs

Li Chen's Blog

Custom Web API Message Formatter

ASP.NET Web API supports multiple message formats. The framework uses the “Accept” request header from the client to determine the message format. If you visit a Web API URL with internet explorer, you will get a JSON message by default; if you use Chrome, which sends “application/xml;” in the accept header, you will get a XML message.

Message format is an extensivity point in Web API. There is a pretty good example on ASP.NET web site. Recently, when I worked on my SkyLinq open source cloud analytic project, I needed a way to expose data to the client in a very lean manner. I would like it to leaner than both XML and JSON, so I used csv. The example provided on the ASP.NET website is actually a CSV example. The article was lastly updated on March 8, 2012. Since ASP.NET is rapidly advancing, I found that I need to make the following modifications to make the example working correctly with Web API 2.0.

  1. CanReadType is now a public function instead of a proetected function.
  2. The signature of WriteToStream has changed. The current signature is

    image

  3. When addition the Media Formatter to the Configuration, I have to insert my custom formatter into the formatters collection as the first. This is because the JSON Formatter actually recognizes the “application/csv” header and send JSON back instead. Example below:

    image

Comments

 

sriram said:

Gives me an idea to develop web API Message Formatter using ASP.NET

January 6, 2014 6:32 AM

Leave a Comment

(required)  
(optional)
(required)  
Add