我有一个简单的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;
}
Run Code Online (Sandbox Code Playgroud)
......并从服务界面:
[OperationContract(Name = "GetSampleMethod")]
[WebGet(UriTemplate = "Get/{name}")]
byte[] GetSampleMethod(string name);
Run Code Online (Sandbox Code Playgroud)
它返回一个包含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;
}
Run Code Online (Sandbox Code Playgroud)