.NET – How to return to the stream from WCF services?

I am playing protobuf-net and WCF. This is the code I created:

public class MobileServiceV2
{
[WebGet(UriTemplate = "/some-data")]
[Description("returns test data")]
public Stream GetSomeData()
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-protobuf";

var ms = new MemoryStream();
ProtoBuf.Serializer.Serialize(ms, new MyResponse {SomeData = "Test data here" });
return ms;
}
}

[DataContract]
public class MyResponse
{
[DataMember(Order = 1)]
public string SomeData {get; set; }
}

When I see Fiddler-I can see the correct outgoing The content type, and they all look good, but I get a hollow response. IE prompts to download the file, this file is empty. Does the serializer not work? Or am I just not doing it right?

Edit:

I added the following code in the method, yes, it serializes correctly. What’s wrong with how I return the stream from WCF..

using (var file = File.Create("C:\test.bin"))
{
Serializer.Serialize(file, new MyResponse {SomeData = "Test data here" });
}

just write to MemoryStream, then go back That’s right. Don’t Dispose() it in this case:

var ms = new MemoryStream();
Serializer.Serialize(ms, obj );
ms.Position = 0;
return ms;

However, this does mean that it is buffered in memory. I can try to come up with some voodoo to avoid this This situation, but it will be very complicated.

I am playing protobuf-net and WCF. This is the code I created:

public class MobileServiceV2
{
[WebGet(UriTemplate = "/some-data")]
[Description("returns test data")]
public Stream GetSomeData()
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-protobuf";

var ms = new MemoryStream();
ProtoBuf.Serializer.Serialize(ms, new MyResponse { SomeData = "Test data here" });
return ms;
}
}

[DataContract]
public class MyResponse
{
[DataMember(Order = 1)]
public string SomeData {get; set; }
}

When I see Fiddler – I can see the correct The content type is sent out, and they all look good, but I get a hollow response. IE prompts to download the file, this file is empty. Is the serializer not working? Or am I just not doing it right?

Edit:

I added the following code in the method, yes, it serializes correctly. What’s wrong with how I return the stream from WCF..

using (var file = File.Create("C:\test.bin"))
{
Serializer.Serialize(file, new MyResponse {SomeData = "Test data here" });
}

Just write to the MemoryStream and then go back. Don’t Dispose() in this case It:

var ms = new MemoryStream();
Serializer.Serialize(ms, obj);
ms.Position = 0;
return ms;

However, this does mean that it is buffered in memory. I can try to come up with some voodoo to avoid this, but it will be very complicated.

Leave a Comment

Your email address will not be published.