Returning an Azure BLOB from a WCF service as a stream. Do I need to close it?

I have a simple WCF service that provides a REST endpoint and retrieves files from a BLOB container. The service returns the file as a stream. I came across this message about closing the stream after the response was received:

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 questions:

  • Should I follow the pattern given in the message?
  • If I change my return type to Byte [], what is Cons / Pros?

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

0
source share
2 answers

OperationBehaviorAttribute.AutoDisposeParameters is by default set to TRUE, which is called on all 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.

0
source

I would like to change the return type to byte[] . This is more neat.

Stream implements IDisposable , so theoretically the consumer of your method would have to call your code in the using block:

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

If your client definitely needs access to what Stream provides, then by all means execute it and return it, but by returning byte[] , you will control any unmanaged resources hidden under the covers.

0
source

Source: https://habr.com/ru/post/1383206/


All Articles