WCF 服务端点处的空流

Empty stream at the end point of WCF service

我有 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?,我认为其中没有错误,据我所知,我得到的是空流。

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

如果您按如下方式更新方法 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;
}