2011-12-12 175 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

和合同? –