开发者

How to transfer MemoryStream via WCF Streaming

开发者 https://www.devze.com 2023-04-06 09:04 出处:网络
I am planning to pass MemoryStream via WCF St开发者_JAVA技巧reaming but it seems not working but when I slightly change the code to pass FileStream instead, it is working. In fact, my purpose is to pa

I am planning to pass MemoryStream via WCF St开发者_JAVA技巧reaming but it seems not working but when I slightly change the code to pass FileStream instead, it is working. In fact, my purpose is to pass large collection of business objects (serializable). I am using basicHttpBinding. Your suggestion would be much appreciated!

Edited: The symptoms of the issue is that the incoming stream is empty. There is neither error nor exception.


You're not providing many details, however, I'm almost certain I know what the issue is as I've seen that happening a lot.

If you write something to a MemoryStream in order to return that one as the result of a WCF service operation, you need to manually reset the stream to its beginning before returning it. WCF will only read the stream from it current position, hence will return an empty stream if that position hasn't been reset.

That would at least explain the problem you're describing. Hope this helps.

Here some sample code:

    [OperationContract]
    public Stream GetSomeData()
    {
        var stream = new MemoryStream();
        using(var file = File.OpenRead("path"))
        {
            // write something to the stream:
            file.CopyTo(stream);         
            // here, the MemoryStream is positioned at its end
        }
        // This is the crucial part:
        stream.Position = 0L;
        return stream;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号