Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "The inner stream position has changed unexpectedly" in AWS Lambda

I am implementing a file upload in ASP.Net core. Everything works fine when testing locally on Windows but when I deploy my code on AWS Lambda, I am getting

"System.InvalidOperationException: The inner stream position has changed unexpectedly. at Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.VerifyPosition() at Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.Read(Byte[] buffer, Int32 offset, Int32 count) at System.IO.Stream.CopyTo(Stream destination, Int32 bufferSize)"

My code:

[HttpPost]
[Route("")]
[Authorize]
public IActionResult Store([FromForm] MyFiles files)
{
    var stream1 = files.File1.OpenReadStream();
    var stream2 = files.File2.OpenReadStream();
    string result;
    using (MemoryStream ms = new MemoryStream())
    {
        stream1.CopyTo(ms);
        ms.Position = 0;
        result= GetCrcForFile(ms);
    }
}

public class MyFiles
{
    public IFormFile File1 { get; set; }
    public IFormFile File2 { get; set; }
}

public string GetCrcForFile(Stream result)
{
    uint crc = 0;
    using (MemoryStream ms = new MemoryStream())
    {
        result.CopyTo(ms);
        var bytes = ms.ToArray();
        crc = Crc32Algorithm.Compute(bytes);
        return crc.ToString("X");
    }
}

The exception happens on line result.CopyTo(ms);

I am not sure if it is .Net Core behaving differently on Linux environment or AWS Lambda issue or I am doing something wrong.

like image 238
Yahya Hussein Avatar asked Oct 16 '25 13:10

Yahya Hussein


1 Answers

As indicated in this issue, depending on what kind of server you're using, you cannot access the file streams in just any order. You need to open and process the files in sequential order, or you'll receive this "The inner stream position has changed unexpectedly" exception.

Therefore, make sure to:

  • Call OpenReadStream on File1, then fully process the contents of the file
  • Only then, call OpenReadStream on File2, and so on
like image 144
Kevin Gosse Avatar answered Oct 18 '25 14:10

Kevin Gosse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!