我有WCF服务,我指定通过streames使用: 这是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?我认为它没有错误,所以据我所知,我得到了空的流。
答案 0 :(得分: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;
}