0

Good afternoon, I need to implement a partial dowload file, for example, I will have a 2GB document, and I want them to be sent to the server a little, for the test I have a folder with 20 mb and I will send 1 mb, but unfortunately I get mistake System.InvalidOperationException: 'Headers are read-only, response has already started.'

  [HttpGet("Download")]
        public async Task DownloadFile()
        {
            var response = HttpContext.Response;
            var fileStream = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var buffer = new byte[1024* 1024]; // 1 MB buffer
            var totalBytesSent = 0L;
    
            try
            {
                response.ContentType = "application/octet-stream";
                response.StatusCode = (int)HttpStatusCode.PartialContent;
                response.Headers.Add("Content-Disposition", $"attachment; filename={Path.GetFileName(_filePath)}");
                response.Headers.Add("Content-Length", fileStream.Length.ToString());
    
                int bytesRead;
                while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    totalBytesSent += bytesRead;
    
                    response.Headers["Content-Range"] =
                        $"bytes {totalBytesSent - bytesRead}-{totalBytesSent - 1}/{fileStream.Length}";
    
                    await response.Body.WriteAsync(buffer, 0, bytesRead);
                    await response.Body.FlushAsync();
                }
    
                response.StatusCode = (int)HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                fileStream.Dispose();
            }
        }

0 Answers0