Lui*_*cia 0 .net c# asp.net asp.net-mvc asp.net-core
我有一个REST API,它必须从AWS服务器的远程URL获取文件.该文件已下载,但当我尝试打开它时,它没有显示任何内容,如损坏.
没有异常被抛出
代码是这样的
[HttpPost]
[Route("api/[controller]/UploadFileToAzureStorage")]
public async Task<IActionResult> GetFile([FromBody]PDF urlPdf)
{
string localFilePath = CreateTemporaryFile(urlPdf.urlPDF);
// Create storage account
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageAccount);
// Create a blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Get a reference to a container named "mycontainer."
CloudBlobContainer container = blobClient.GetContainerReference(UploaderStorage.Container);
// Get a reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
// Create or overwrite the "myblob" blob with the contents of a local file
// named "myfile".
using (var fileStream = System.IO.File.OpenRead(localFilePath))
{
await blockBlob.UploadFromStreamAsync(fileStream);
}
return Ok();
}
/// <summary>
/// Creates temporary file
/// </summary>
/// <param name="urlPdf">PDF URL</param>
/// <returns>Returns path of the new file</returns>
private string CreateTemporaryFile(string urlPdf)
{
Uri uri = new Uri(urlPdf);
string filename = default(string);
//if (uri.IsFile)
//{
filename = System.IO.Path.GetFileName(uri.LocalPath);
//}
try
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response =
client.GetAsync(urlPdf, HttpCompletionOption.ResponseHeadersRead).Result)
{
response.EnsureSuccessStatusCode();
using (Stream contentStream = response.Content.ReadAsStreamAsync().Result, fileStream = new FileStream(@"\\pc030\TemporaryPDF\"+ filename,
FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
var buffer = new byte[8192];
var isMoreToRead = true;
do
{
var read = contentStream.ReadAsync(buffer, 0, buffer.Length).Result;
if (read == 0)
{
isMoreToRead = false;
}
else
{
fileStream.WriteAsync(buffer, 0, read);
}
}
while (isMoreToRead);
}
}
}
return @"\\pc030\TemporaryPDF\" + filename;
}
catch(Exception ex)
{
throw ex;
}
}
Run Code Online (Sandbox Code Playgroud)
response.Content.ReadAsStreamAsync().Result
并且contentStream.ReadAsync(buffer, 0, buffer.Length).Result
是一个等待你的代码中的僵局炸弹.
Task.Result
除非您完全理解这样做的含义,否则永远不要在UI代码或服务器代码中等待.
服务器和UI都使用特殊的方法SynchronizationContext
将异步延迟调度回调用线程.当同一个线程已挂起,等待时Result
,一切都可以锁定.
阅读和摘要:
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
你的CreateTemporaryFile
方法应该被标记async
,你应该进行await
这些调用.
所以,对你的问题.你在fileStream.WriteAsync(buffer, 0, read)
没有await
任务完成的情况下打电话.在(至少)最后一次写入时,流将在写入完成之前被处理,具有可预测的结果.
采取async
适当或根本不使用它.没有中途宿舍.
归档时间: |
|
查看次数: |
489 次 |
最近记录: |