繁体   English   中英

如何在Windows Azure上运行的WCF服务中返回文件?

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

我有一个简单的Web服务,我想创建一个方法,该方法将向我返回一个文本文件。 我这样做是这样的:

    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序列化的情况下返回文件?

更改您的方法以返回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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM