Getting “The inner stream position has changed unexpectedly” in AWS Lambda

房东的猫 提交于 2021-01-28 11:38:49

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/55674322/getting-the-inner-stream-position-has-changed-unexpectedly-in-aws-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!