Cli*_*ane 1 c# asynchronous asp.net-web-api azure-blob-storage
我很难弄清楚出了什么问题。我的应用程序访问 api 来获取文档。发生的情况是下载开始,但挂起。最终它会完成(要么有错误,要么完全完成),但是当我尝试打开 pdf 时,我收到“无法打开 pdf”或类似的信息。它在本地工作。
我的控制器:
[Route("api/listing/attachment")]
[HttpGet]
public async Task<IHttpActionResult> GetAttachmentAsync(string fileName)
{
var attachment = await _repository.GetAttachmentAsync(fileName);
var response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/x-download";
var removePath = fileName.Substring(fileName.IndexOf("/", fileName.IndexOf("/", StringComparison.Ordinal) + 1, StringComparison.Ordinal) + 1);
response.AddHeader("content-disposition", string.Format("attachment; filename={0}", removePath));
response.AddHeader("content-length", attachment.Length.ToString());
response.BinaryWrite(attachment);
response.Flush();
return null;
}
Run Code Online (Sandbox Code Playgroud)
我的存储库:
public async Task<byte[]> GetAttachmentAsync(string fileName)
{
var container = _blobClient.GetContainerReference(_containerName);
var blockBlob = container.GetBlockBlobReference(fileName);
using (var memoryStream = new MemoryStream())
{
await blockBlob.DownloadToStreamAsync(memoryStream);
return memoryStream.ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
尝试将控制器代码更改为:
[Route("api/listing/attachment")]
[HttpGet]
public async Task<HttpResponseMessage> GetAttachmentAsync(string fileName)
{
var attachment = await _repository.GetAttachmentAsync(fileName);
var removePath = fileName.Substring(fileName.IndexOf("/", fileName.IndexOf("/", StringComparison.Ordinal) + 1, StringComparison.Ordinal) + 1);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(attachment)
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = removePath
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3518 次 |
| 最近记录: |