ASP.NET Web API request processing not quite the same as MVC

Web API is an awesome new capability for web services.  One tidbit that I'm putting here for people searching is that:

The request body can only be read once!  In MVC and HttpContext, the request is stored so that it can be parsed over and over.  In Web API, with an eye to performance, the Body is just a stream.  Once it has been read, a subsequent read will fail because you are at the end of the stream.

That means that when you plan your model binding, you can only use one complex object.  The rest need to be bound some other way, either via the querystring or URI.

Here is an article that explains this is much more detail:

http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

Comments

Filip W said on 1.26.2013 at 1:08 PM

HttpContent exposes and HttpContent.LoadIntoBuffer() method which allows you to buffer the body on demand.

In fact a few methods that allow you to read the body (i.e. in the handler or filter) - ReadAsStringAsync, ReadAsByteArrayAsync - DO buffer the request content internally (the call LoadIntoBuffer themselves), so after using these methods, you would still be able to access the body of the request again.