如何从WCF服务返回流? [英] How to return stream from WCF service?

查看:74
本文介绍了如何从WCF服务返回流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用protobuf-net和WCF。这是我创建的代码:

I'm playing with protobuf-net and WCF. Here is 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; }
}

当我查看Fiddler时-可以看到正确的传出内容类型和一切看起来不错,但是我得到的回应是空洞的。 IE提示下载文件,该文件为空。序列化器不起作用吗?还是我做错了?

When I look in Fiddler - I can see proper outgoing content-type and all looks good, but I get empty response. IE prompts to download file and this file is empty. Is serializer not working? Or I just don't do it right?

编辑:

我在方法中添加了以下代码,是的,它可以正确地序列化。我从WCF返回流的方式出了点问题。

I added following code to method and yes, it serializes correctly. Something wrong with how I return stream from WCF..

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


推荐答案

只需写入MemoryStream,然后倒带在这种情况下,请 Dispose():

Just write to a MemoryStream, and rewind it. Do not Dispose() it in this case:

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

但是,这确实意味着它在内存中进行缓冲。我可以尝试并想出一些伏都教徒来避免这种情况,但这会非常复杂。

This does, however, mean that it buffers in memory. I could try and come up with some voodoo to avoid that, but it would be very complex.

这篇关于如何从WCF服务返回流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆