如何通过WCF Streaming传输MemoryStream

发布于 2024-12-05 20:38:32 字数 182 浏览 3 评论 0原文

我计划通过 WCF Streaming 传递 MemoryStream 但它似乎不起作用,但是当我稍微更改代码以传递 FileStream 时,它就起作用了。事实上,我的目的是传递大量业务对象的集合(可序列化)。我正在使用 basicHttpBinding。非常感谢您的建议!

编辑: 该问题的症状是传入流为空。既没有错误也没有异常。

I am planning to pass MemoryStream via WCF Streaming 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

—━☆沉默づ 2024-12-12 20:38:32

您没有提供很多细节,但是,我几乎可以肯定我知道问题是什么,因为我已经看到这种情况发生了很多。

如果您向 MemoryStream 写入某些内容以便将其作为 WCF 服务操作的结果返回,则需要在返回之前手动将流重置到其开头。 WCF 只会从当前位置读取流,因此如果该位置尚未重置,将返回一个空流。

这至少可以解释你所描述的问题。希望这有帮助。

这里有一些示例代码:

    [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;
    }

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;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文