Returning Azure BLOB from WCF service as a Stream

2019-03-06 14:11发布

问题:

I have a simple WCF service that exposes a REST endpoint, and fetches files from a BLOB container. The service returns the file as a stream. i stumbled this post about closing the stream after the response has been made :

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

This is my code:

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;
      }
}

So I have two question :

  1. Should I follow the pattern mentioned in the post ?
  2. If I change my return type to Byte[], what are Cons/Pros ?

( My client is Silverlight 4.0, just in case it has any effect )

回答1:

I'd consider changing your return type to byte[]. It's tidier.

Stream implements IDisposable, so in theory the consumer of your method will need to call your code in a using block:

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

If your client definitely needs access to something that Stream provides, then by all means go ahead and return that, but by returning a byte[] you keep control of any unmanaged resources that are hidden under the covers.



回答2:

OperationBehaviorAttribute.AutoDisposeParameters is set to TRUE by default which calls dispose on all the inputs/outputs that are disposable. So everything just works.
This link :
http://devdump.wordpress.com/2008/12/07/disposing-return-values/
explains how to manually control the process.