C# 通过c加载时PDF文件已损坏

C# 通过c加载时PDF文件已损坏,c#,asp.net,.net,asp.net-mvc,asp.net-core,C#,Asp.net,.net,Asp.net Mvc,Asp.net Core,我有一个RESTAPI,它必须从AWS服务器中的远程URL获取文件。该文件已下载,但当我尝试打开它时,它没有显示任何内容,例如已损坏 没有抛出异常 代码是这样的 [HttpPost] [Route("api/[controller]/UploadFileToAzureStorage")] public async Task<IActionResult> GetFile([FromBody]PDF urlPdf) {

我有一个RESTAPI,它必须从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;
            }
        }
response.Content.ReadAsStreamAsync.Result和contentStream.ReadAsyncbuffer,0,buffer.Length.Result是一个等待在代码中引爆的死锁炸弹

永远不要因为等待任务而阻塞。除非您完全理解这样做的含义,否则将生成UI代码或服务器代码

服务器和UI都使用一个特殊的SynchronizationContext,它将异步继续调度回调用线程。当同一个线程已经挂起,等待结果时,一切都可以锁定

阅读和摘要:

您的CreateTemporaryFile方法应该标记为async,并且您应该等待这些调用

所以,解决你的问题。您正在调用fileStream.WriteAsyncbuffer,0,在不等待任务完成的情况下读取。在至少最后一次写入时,流将在写入完成之前被释放,并具有可预测的结果

正确地采用async,或者根本不使用它。没有中途宿舍