简体   繁体   English

c#-流的意外结束,该内容可能已被另一个组件读取

[英]c# - Unexpected end of Stream, the content may have already been read by another component

I've been trying to get this to work, but no luck. 我一直在努力使它工作,但是没有运气。

I have middleware class where used to verify uploaded files. 我有用于验证上传文件的中间件类。

After middleware debug goes to the Controller class, but not to the action. 在中间件调试之后,将转到Controller类,但不会进行操作。 Context Request ending after controller's constructor. 上下文请求在控制器的构造函数之后结束。

Middleware class: 中间件类:

 public class UploadMiddleware
{

    public UploadMiddleware(RequestDelegate next)
    {
        _next = next;
    }

        [DisableFormValueModelBinding]
        [ValidateAntiForgeryToken]
    public async Task Invoke(HttpContext context)
    {
        var authToken = context.Request.Headers["id"].ToString();
        var path = context.Request.Path.ToString();
        var streamBody = context.Request.Body;

            if (authToken != String.Empty)
            {
                if (!IsMultipartContentType(context.Request.ContentType))
                {
                    await context.Response.WriteAsync("Unexpected error.");  
                    await _next(context);              
                    return;
                }

                var boundary = GetBoundary(context.Request.ContentType); 
                var reader = new MultipartReader(boundary, context.Request.Body);
                // reader.HeadersLengthLimit = int.MaxValue;
                // reader.BodyLengthLimit = long.MaxValue;

                var section = await reader.ReadNextSectionAsync();
                var buffer = new byte[256];
                while (section != null)
                {
                    var fileName = GetFileName(section.ContentDisposition);
                    var bytesRead = 0;

                    using (var stream = new FileStream(fileName,FileMode.Append))
                    {                                         
                        do{

                            bytesRead = await section.Body.ReadAsync(buffer, 0, buffer.Length);
                            stream.Write(buffer, 0, bytesRead);       
                             buffer = Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(buffer));
                       } while (bytesRead < 0);                   
                    }


                    if (!verifyUpcomingFiles(buffer))
                    {
                        await context.Response.WriteAsync("Undefined file type detected.");
                        return;
                    }
                     else
                     {
                      context.Request.Headers.Add("isVerified","verified");                                                    
                    }


                     section = await reader.ReadNextSectionAsync();      
                }


            }
            else
            {
                await context.Response.WriteAsync("You are not allowed to complete this process.");
                return;

            }
            await _next(context);


    }

I am stuck in this problem. 我陷入了这个问题。 I really need someone point me in a direction, that would be greatly appreciated. 我真的需要有人指出我的方向,这将不胜感激。

The error message is pretty clear, as well as the docs are and warns you about it in big red box : 错误消息非常清晰, 文档也很清楚,并在红色大框内警告您:

Warning 警告

Do not call next.Invoke after the response has been sent to the client. 不要调用next.Invoke发送到客户端后调用。 Changes to HttpResponse after the response has started will throw an exception. 开始响应后,对HttpResponse更改将引发异常。 For example, changes such as setting headers, status code, etc, will throw an exception. 例如,诸如设置标题,状态代码等更改将引发异常。 Writing to the response body after calling next : 在调用next之后写入响应主体:

  • May cause a protocol violation. 可能会导致违反协议。 For example, writing more than the stated content-length. 例如,写的内容多于规定的内容长度。

  • May corrupt the body format. 可能会破坏主体格式。 For example, writing an HTML footer to a CSS file. 例如,将HTML页脚写入CSS文件。

HttpResponse.HasStarted is a useful hint to indicate if headers have been sent and/or the body has been written to. HttpResponse.HasStarted是一个有用的提示,用于指示是否已发送标头和/或已写入正文。

if (!IsMultipartContentType(context.Request.ContentType))
{
    await context.Response.WriteAsync("Unexpected error.");  
    // Here you're calling the next middleware after writing to the response stream!
    await _next(context);              
    return;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Stream 意外结束,内容可能已被其他组件读取 - Unexpected end of Stream, the content may have already been read by another component IOException: Stream 意外结束,内容可能已被另一个组件读取 - IOException: Unexpected end of Stream, the content may have already been read by another component 意外结束 Stream,内容可能已被另一个组件读取。 Microsoft.AspNetCore.WebUtilities.MultipartReaderStream - Unexpected end of Stream, the content may have already been read by another component. Microsoft.AspNetCore.WebUtilities.MultipartReaderStream C#-将数据写入流+与另一个流读取数据 - C# - Write Data To A Stream + Read Data With Another Stream 在C#中读取流 - Read stream in C# C#有效读取流内容并限制读取量 - C# efficient reading of stream content with a limit on amount read C#multipart / form-data MIME多部分流的意外结尾 - C# multipart/form-data Unexpected end of MIME multipart stream 项目不存在。 它可能已被其他用户删除 - Item does not exist. It may have been deleted by another user 跟踪已经完成了哪些递归调用-C# - Keeping track of which recursive calls have been done already - C# C#和Razor - 您已请求的页面类型未被提供,因为它已被明确禁止。 扩展名“.cshtml”可能不正确 - C# and Razor - The type of page you have requested is not served because it has been explicitly forbidden. The extension '.cshtml' may be incorrect
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM