在 AWS Lambda 中获取 "The inner stream position has changed unexpectedly"
Getting "The inner stream position has changed unexpectedly" in AWS Lambda
我正在 ASP.Net 核心实现文件上传。
在 Windows 上本地测试时一切正常,但是当我在 AWS Lambda 上部署我的代码时,我得到
"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)"
我的代码:
[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");
}
}
异常发生在行 result.CopyTo(ms);
我不确定是 .Net Core 在 Linux 环境或 AWS Lambda 问题上表现不同,还是我做错了什么。
如 in this issue 所示,根据您使用的服务器类型,您无法按任意顺序访问文件流。您需要按顺序打开和处理文件,否则您将收到此 "The inner stream position has changed unexpectedly" 异常。
因此,请确保:
- 在
File1
上调用 OpenReadStream
,然后完全处理文件的内容
- 然后,在
File2
上调用 OpenReadStream
,依此类推
我正在 ASP.Net 核心实现文件上传。 在 Windows 上本地测试时一切正常,但是当我在 AWS Lambda 上部署我的代码时,我得到
"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)"
我的代码:
[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");
}
}
异常发生在行 result.CopyTo(ms);
我不确定是 .Net Core 在 Linux 环境或 AWS Lambda 问题上表现不同,还是我做错了什么。
如 in this issue 所示,根据您使用的服务器类型,您无法按任意顺序访问文件流。您需要按顺序打开和处理文件,否则您将收到此 "The inner stream position has changed unexpectedly" 异常。
因此,请确保:
- 在
File1
上调用OpenReadStream
,然后完全处理文件的内容 - 然后,在
File2
上调用OpenReadStream
,依此类推