【问题标题】:Empty stream at the end point of WCF serviceWCF 服务端点处的空流
【发布时间】:2015-06-02 19:21:43
【问题描述】:

我有 WCF 服务,我指定通过流使用它: 这是 Web.config

<services>
  <service name="StreamServiceBL">
    <endpoint address="" binding="basicHttpBinding"
      bindingConfiguration="StreamServiceBLConfiguration" contract="IStreamServiceBL" />
  </service>
</services>
<bindings>
   <basicHttpBinding>
    <binding name="StreamServiceBLConfiguration" transferMode="Streamed"/>
  </basicHttpBinding>
</bindings>

这是我发送流媒体的方式:

    private static MemoryStream SerializeToStream(object o)
    {
        var stream = new MemoryStream();
        IFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, o);
        return stream;
    }

    private void Somewhere()
    {
        //...
        streamServiceBLClientSample.MyFunc(SerializeToStream(myObject));
    }

这就是我收到它们的方式:

[ServiceContract]
public interface IStreamServiceBL
{
    [OperationContract]
    public int MyFunc(Stream streamInput);
}

public class StreamServiceBL : IStreamServiceBL
{
    public int MyFunc(Stream streamInput)
    {
        //There I get exception: It can't to deserialize empty stream
        var input = DeserializeFromStream<MyType>(streamInput);

    }

    public static T DeserializeFromStream<T>(Stream stream)
    {
        using (var memoryStream = new MemoryStream())
        {
            CopyStream(stream, memoryStream);

            IFormatter formatter = new BinaryFormatter();
            memoryStream.Seek(0, SeekOrigin.Begin);
            object o = formatter.Deserialize(memoryStream); //Exception - empty stream
            return (T)o;
        }
    }

    public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[16 * 1024];
        int read;
        //There is 0 iteration of loop - input is empty
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, read);
        }
    }
}

所以我花的不是一个空流,而是一个空流。我从那里得到 CopyStream 代码:​​How to get a MemoryStream from a Stream in .NET?,我认为其中没有错误,所以据我所知,我得到了空流。

【问题讨论】:

  • 您有问题吗?
  • 是的,我总是得到一个 EMPTY 流。但我不花空流。我怎样才能改变它?

标签: c# wcf


【解决方案1】:

很难说为什么在一般情况下你会得到一个空流,但在你的示例情况下,它是非常清楚的。

如果您将方法 SerializeToStream 更新如下,一切都应该按预期工作:

private static MemoryStream SerializeToStream(object o)
{
    var stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    // here we reset stream position and it can be read from the very beginning
    stream.Position = 0;  
    return stream;
}

【讨论】:

  • 不,它不起作用。我添加了一些新代码。我希望它有所帮助。
  • @RustamSalahutdinov,您真的按照我的建议更新了SerializeToStream(在客户端,而不是服务器)吗?我刚刚测试过,没有更新,我在服务器上也得到了一个空蒸汽,有了更新,我得到了预期的数据。
  • 首先,我在序列化之前插入它并没有看到它。在你提醒我之后 - 我将它替换到正确的位置并且它有效!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
  • 2010-09-16
  • 2015-08-20
  • 1970-01-01
相关资源
最近更新 更多