2011-12-12 96 views
5

我有一个为JSON数据结构提供服务的WCF Rest服务项目。我已经定义在接口文件就像一个合同:在WCF REST服务中返回非JSON,非XML数据

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

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

喜欢的东西:

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

这样:如下图所示wget http://example.com/multimedia/10返回id为10

+0

看看这个:http://stackoverflow.com/questions/2992095/attaching-files-to-wcf-rest-service-responses – pdiddy

+0

谢谢你pdiddy它解决了这个问题,并包含一些有趣的额外信息。 – Pierre

回答

3

PDF文档您可以从您的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); 
     } 

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

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

+0

谢谢。请注意,文本文件的内容类型通常是“text/plain”。 – Pierre

+0

和合同? –