1

我有一个简单的 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 序列化的文件?

4

1 回答 1

9

更改您的方法以返回 a 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;
}
于 2012-04-11T18:56:41.820 回答