0

I've created a middleware delegate in a brand new blazor-server project, to transform my html responses. See code below.


            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);
                }
            });

But when I compare a string extracted from the Response.ContentType, I'm getting an exception (image 1). But when comparing another string with the same value, I'm not getting it (image 2) In both cases the page is rendered with the replacement. Any help on this one?

Image 1 Image 1

Image 2 Image 2

1

1 Answer 1

0

Actually, the Exception occurs when the response content type is NOT "text/html" (of course, in other requests)

The real cause is that I'm assigning the body a new stream but never restoring the originalStream, which is wrong.

But even assigning it afterwards does not work. This is the final solution I've managed to work, please, see the comments en the IF statements.

            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;
            });
Sign up to request clarification or add additional context in comments.

1 Comment

BTW, I was trying to use the solutions proposed in here: stackoverflow.com/questions/44508028/modify-middleware-response/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.