得到“内部流位置已经意外改变".在AWS Lambda中 [英] Getting "The inner stream position has changed unexpectedly" in AWS Lambda

查看:136
本文介绍了得到“内部流位置已经意外改变".在AWS Lambda中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ASP.Net core中实现文件上传.在Windows上进行本地测试时,一切正常,但是当我在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:内部流的位置已意外更改.在Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.VerifyPosition()在Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.Read(Byte []缓冲区,Int32偏移量,Int32计数)在System.IO.Stream.CopyTo(流目标,Int32 bufferSize)"

"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问题上表现出不同,或者我做错了事.

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

推荐答案

如本问题所述,取决于您使用的是哪种服务器,您不能以任何顺序访问文件流.您需要按顺序打开和处理文件,否则将收到此内部流位置发生意外更改"的异常.

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.

因此,请确保:

  • File1 上调用 OpenReadStream ,然后完全处理文件的内容
  • 然后,仅在 File2 上调用 OpenReadStream ,依此类推
  • Call OpenReadStream on File1, then fully process the contents of the file
  • Only then, call OpenReadStream on File2, and so on

这篇关于得到“内部流位置已经意外改变".在AWS Lambda中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆