0

我有一個簡單的WCF服務公開REST端點,並從BLOB容器中獲取文件。該服務將該文件作爲流返回。我無意中發現這個帖子關於關閉流的響應作出後:從WCF服務返回Azure BLOB作爲流 - 我們需要關閉它嗎?

http://devdump.wordpress.com/2008/12/07/disposing-return-values/

這是我的代碼:

public class FileService 
{ 
    [OperationContract] 
    [WebGet(UriTemplate = "{*url}")] 
    public Stream ServeHttpRequest(string url) 
    {         
     var fileDir = Path.GetDirectoryName(url); 
     var fileName = Path.GetFileName(url); 
     var blobName = Path.Combine(fileDir, fileName); 
     return getBlob(blobName);                   
    } 

    private Stream getBlob(string blobName) 
    { 
     var account = CloudStorageAccount.FromConfigurationSetting("ConnectingString"); 
     var client = account.CreateCloudBlobClient(); 
     var container = client.GetContainerReference("data"); 
     var blob = container.GetBlobReference(blobName); 

     MemoryStream ms = new MemoryStream();   
     blob.DownloadToStream(ms); 
     ms.Seek(0, SeekOrigin.Begin);         
     return ms; 
     } 
} 

所以,我有兩個問題:

  1. 我應該遵循帖子中提到的模式?
  2. 如果我將返回類型更改爲Byte [],什麼是缺點/優點?

(我的客戶是Silverlight的4.0,以防萬一有任何影響)

回答

0

我會考慮改變你的返回類型byte[]。它更整潔。

Stream實現IDisposable,所以理論上你的方法的消費者將需要調用你的代碼在using塊:

using (var receivedStream = new FileService().ServeHttpRequest(someUrl)) 
{ 
    // do something with the stream 
} 

如果你的客戶肯定需要訪問的東西,Stream提供,然後通過各種手段繼續並返回,但通過返回byte[]您可以控制隱藏在封面下的任何非託管資源。