在WCF REST服务中返回非JSON,非XML数据

Pie*_*rre 5 .net c# wcf

我有一个WCF Rest服务项目设置服务JSON数据结构.我在接口文件中定义了一个合同,如:

[OperationContract]
[WebInvoke(Method = "GET",
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "location/{id}")]
Location GetLocation(string id);
Run Code Online (Sandbox Code Playgroud)

现在,WebService需要像标准Web服务器一样返回多媒体(图像,PDF文档)文档.在WCF WebMessageFormat中的ResponseFormat唯一支持JSON或XML.如何在界面中定义方法以返回文件?

就像是:

[OperationContract]
[WebInvoke(Method="GET",
    ResponseFormat = ?????
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "multimedia/{id}")]
???? GetMultimedia(string id);
Run Code Online (Sandbox Code Playgroud)

这样:wget http://example.com/multimedia/10返回id为10的PDF文档.

Raj*_*esh 4

您可以从 RESTful 服务获取文件,如下所示:

[WebGet(UriTemplate = "file")]
        public Stream GetFile()
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt";
            FileStream f = new FileStream("C:\\Test.txt", FileMode.Open);
            int length = (int)f.Length;
            WebOperationContext.Current.OutgoingResponse.ContentLength = length;
            byte[] buffer = new byte[length];
            int sum = 0;
            int count;
            while((count = f.Read(buffer, sum , length - sum)) > 0 )
            {
                sum += count;
            }
            f.Close();
            return new MemoryStream(buffer); 
        }
Run Code Online (Sandbox Code Playgroud)

当您在 IE 中浏览到该服务时,它应该显示一个打开的响应保存对话框。

注意:您应该为服务返回的文件设置适当的内容类型。在上面的示例中,它返回一个文本文件。