问题
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
onFile1
, then fully process the contents of the file - Only then, call
OpenReadStream
onFile2
, and so on
来源:https://stackoverflow.com/questions/55674322/getting-the-inner-stream-position-has-changed-unexpectedly-in-aws-lambda