kavalerov
kavalerov

Reputation: 390

How to return file in WCF service running on Windows Azure?

I have a simple web service and I want to make a method which will return me a single text file. I did that this way:

    public byte[] GetSampleMethod(string strUserName)
    {
        CloudStorageAccount cloudStorageAccount;
        CloudBlobClient blobClient;
        CloudBlobContainer blobContainer;
        BlobContainerPermissions containerPermissions;
        CloudBlob blob;
        cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
        blobClient = cloudStorageAccount.CreateCloudBlobClient();
        blobContainer = blobClient.GetContainerReference("linkinpark");
        blobContainer.CreateIfNotExist();
        containerPermissions = new BlobContainerPermissions();
        containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
        blobContainer.SetPermissions(containerPermissions);
        string tmp = strUserName + ".txt";
        blob = blobContainer.GetBlobReference(tmp);
        byte[] result=blob.DownloadByteArray();
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename="+strUserName + ".txt");
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
        WebOperationContext.Current.OutgoingResponse.ContentLength = result.Length;
        return result;
    }

...and from service interface:

    [OperationContract(Name = "GetSampleMethod")]
    [WebGet(UriTemplate = "Get/{name}")]
    byte[] GetSampleMethod(string name);

And it returns me a test file containing XML response. So the question is: how do I return a file without XML serialization?

Upvotes: 1

Views: 3685

Answers (1)

Brian Reischl
Brian Reischl

Reputation: 7356

Change your method to return a Stream instead. Also, I would suggest not downloading the entire content to a byte[] before returning it. Instead just return the stream from the Blob. I've attempted to adapt your method, but this is freehand code so it may not compile or run as-is.

public Stream GetSampleMethod(string strUserName){
  //Initialization code here

  //Begin downloading blob
  BlobStream bStream = blob.OpenRead();

  //Set response headers. Note the blob.Properties collection is not populated until you call OpenRead()
  WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename="+strUserName + ".txt");
  WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
  WebOperationContext.Current.OutgoingResponse.ContentLength = blob.Properties.Length;

  return bStream;
}

Upvotes: 9

Related Questions