Is it possible to return a stream which is part of a complex object as returned data from a Wcf method?
I have checked most of the msdn references on returing stream data with Wcf; such as this one. All of the examples seem to show how to return stream when the method return type is Stream (or parameter is stream).
What I wanted know is can it return the stream if the data is part of complex object property? For example, can GetData() return the Data which contains a stream as shown below:
[DataContract]
public class Data
{
[DataMember]
public string Info { get; set; }
/// <summary>
/// This is the file stream that would be returned to client.
/// </summary>
[DataMember]
public Stream File { get; set; }
}
[ServiceContract()]
public interface IService
{
[OperationContract]
Data GetData();
}
From my initial testing, it seems that this doesn’t work. I get exception on client side (unexpected socket closure). Result is same regardless of DataContractSerialization or XmlSerialization. I have set the required streaming mode with TransferMode.Streamed.
You can’t do that, see this documentation
So the way you’ve written it isn’t going to work for
TransferMode.Streamedhowever nothing at that link explicitly says a property of typeStreamwouldn’t be serialized but from experience I would not expect that to work.Instead you should return a Stream and define the first x bytes as your string
Infofield.thus when writing to the Stream (server side) you would do
Then on the other side you need to read from the stream correctly to get your data out of the stream. What I would suggest is writing 2
intto the stream first. The first would be the size of your infoStr field and the second is the size of your file. On the client size you read these off first then you know how many bytes you need to read.