Reading streamed content from HttpResponseMessage.Content

11,016

Solution 1

There are a couple of issues that might be cropping up.

Reading XML

I don't know if ReadAsStream will work for XmlDocument, but if you can use XDocument it becomes must easier. Regardless, if the WCF rest service returns additional content aside from XML, you will need to deal with that. For example

var stream = response.Content.ReadAsStream();
using (var reader = XmlReader.Create(stream))
{
    XDocument.Load(reader);
}

Headers vs Body

The second issue might be with the way that the response is generated. When the query is made, you can specify if only the headers should read, or if the entire body should be read. Given that the content length is zero, it means that you are getting back a stream of an unknown size. You need handle the stream in that way - loading it into something that can consume the stream properly.

You shouldn't need to use the WebClient, as the HTTP library is made for this stuff.

Erick

Solution 2

For those that are using async - see example below:

HttpResponseMessage response = await task.ExecuteAsync(new CancellationToken());
var yourObject = (YourObject)new XmlSerializer(typeof(YourObject)).Deserialize(new StreamReader( await response.Content.ReadAsStreamAsync()));
Share:
11,016
SmashCode
Author by

SmashCode

Aspiring Android Developer

Updated on June 29, 2022

Comments

  • SmashCode
    SmashCode almost 2 years

    I have a client program that is getting an httpresponsemessage from a WCF rest service. I cannot for the life of me read the content in that response. It says in the content simply "streamed data content" and the content length is 0 and the content type is "".

    I have tried ReadAsStream() and tried to turn the stream into an xml document but I got an error saying the root node is missing.

    I have tried using WebClient but I didn't know what to put in the headers.

    Does anyone know what to do with the "streamed data content" in the content of my response message?