2012-04-11 38 views
1

我有一個簡單的網絡服務,我想做一個方法,將返回給我一個單一的文本文件。我這樣做,是這樣的:如何在Windows Azure上運行的WCF服務中返回文件?

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

...和服務接口:

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

,並返回我包含XML響應測試文件。 所以問題是:如何在沒有XML序列化的情況下返回文件?

+0

您使用什麼客戶端連接到服務並下載文件?由Visual Studio生成的客戶端會自動將其反序列化爲一個字節數組。 – 2012-04-11 14:30:42

+0

我需要它在瀏覽器中工作 – 2012-04-11 14:43:47

+0

是否希望瀏覽器將文件保存爲附件或顯示內容? – 2012-04-11 20:04:30

回答

7

改變你的方法來改爲返回一個Stream。另外,我建議在返回之前不要將整個內容下載到byte []。取而代之的是從Blob返回流。我試圖調整你的方法,但這是手寫代碼,所以它可能不能編譯或按原樣運行。

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; 
} 
相關問題