【问题标题】:ASPNET CORE Middleware strange exceptionASPNET CORE 中间件奇怪的异常
【发布时间】:2020-06-18 10:25:15
【问题描述】:

我在一个全新的 blazor-server 项目中创建了一个中间件委托,以转换我的 html 响应。请参阅下面的代码。


            app.Use(async (context, next) =>
            {
                var originalStream = context.Response.Body;// currently holds the original stream                    
                var newStream = new MemoryStream();
                context.Response.Body = newStream;

                await next(); 

                string contentType1 = context.Response.ContentType?.Split(';', StringSplitOptions.RemoveEmptyEntries)[0];
                string contentType2 = "text/html";

                if (contentType1 == "text/html") // EXCEPTION THROWN, SEE IMAGE 1
                //if (contentType2 == "text/html") // EXCEPTION NOT THROWN, SEE IMAGE 2
                {
                    newStream.Seek(0, SeekOrigin.Begin);
                    var originalContent = new StreamReader(newStream).ReadToEnd();
                    var updatedContent = originalContent.Replace("Hello", "HOLA");

                    context.Response.Body = originalStream;
                    await context.Response.WriteAsync(updatedContent);
                }
            });

但是当我比较从 Response.ContentType 中提取的字符串时,我得到了一个异常(图 1)。但是当比较另一个具有相同值的字符串时,我没有得到它(图 2) 在这两种情况下,页面都是用替换呈现的。对这个有帮助吗?

图片 1

图片 2

【问题讨论】:

标签: middleware blazor-server-side asp.net-core-3.1


【解决方案1】:

其实这个异常发生在响应内容类型不是“text/html”的时候(当然是在其他请求中)

真正的原因是我为正文分配了一个新流,但从未恢复原始流,这是错误的。

但即使事后分配也行不通。这是我设法工作的最终解决方案,请参阅 IF 语句中的 cmets。

            app.Use(async (context, next) =>
            {
                var originalStream = context.Response.Body;           
                var newStream = new MemoryStream();
                context.Response.Body = newStream;

                await next();
                string contentType = context.Response.ContentType?.Split(';', StringSplitOptions.RemoveEmptyEntries)[0];
                //if (contentType == "text/html") //THIS IF -at this level- is still throwing the exceptions for NO text/hteml content type.
                //{

                    newStream.Seek(0, SeekOrigin.Begin);
                    var originalContent = new StreamReader(newStream).ReadToEnd();

                    if (contentType == "text/html") //THIS IF at these level, makes the replacement if needed, but it does not avoid the "Streams operations"
                    {
                        originalContent = originalContent.Replace("Hello", "HOLA");
                    }

                    var memoryStreamModified = GenerateStreamFromString(originalContent);
                    await memoryStreamModified.CopyToAsync(originalStream).ConfigureAwait(false);
                //}
                context.Response.Body = originalStream;
            });

【讨论】:

猜你喜欢
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多