Changes in MediaTypeFormatter: ReadFromStreamAsync/WriteToStreamAsync

Topics: ASP.NET Web API
May 20, 2012 at 10:51 PM
Edited May 20, 2012 at 11:01 PM

I have got a latest build and I noticed a change in the signature of ReadFromStreamAsync/WriteToStreamAsync where instead of HttpContentHeaders, HttpContent is passed in.

My question is, when would I use methods of HttpContent other than the Headers property (which was being passed before as itself). I understand that other operations can be done on the Content such as read/write but then I would do that on the stream.

Is it because I could change the content completely while with read/write from the stream I cannot do that?

Thanks

May 21, 2012 at 12:50 AM

The main reason is that it allows a mediatype formatter to use the various HttpContent.ReadAs* methods which all require HttpContent -- they don't just take a stream or HttpContentHeaders. For example, if somebody wanted to use the ReadAsMultipart extensions within a formatter then it wasn't possible because we didn't expose the HttpContent. Now you can use all the HttpContent.ReadAs* extensions without problems in a media type formatter.

Hope this helps,

Henrik

May 21, 2012 at 9:12 AM

Thanks Henrik. That definitely helped.

Now, my question is, now that we have the HttpContent abstracting the stream, do we need direct access to the stream? We already have access as `ReadAsStreamAsync()` which can be used when stream need for serialization/deserialization.

May 22, 2012 at 4:30 AM

It's merely that it is easier to get the stream directly so that you can pass it to StreamReader etc. right way rather than having to get the stream using a task and then read it.