Skip to content

Middleware that rewrites content seemingly can't change ResponseStream ContentLength #14056

@RickStrahl

Description

@RickStrahl

I have a Live Reload Middleware component that works fine in .NET Core 2.2 but has issues with truncated content in 3.0.

The middleware does a bunch of things, but the part that is problematic has to do with interaction with other content that in this case is output by the StaticFileMiddleware. Basically my middleware creates a new ResponseStream for all output, checks for an HTML response and if it finds it injects a block of script code into the HTML. It does this with a wrapper stream and by intercepting the WriteAsync operations (and overriding a bunch of other ops).

On the outbound pass (at the end of the pipeline) the middleware checks for HTML like this, and if it finds it changes the Response.ContentLength=null:

            // Make sure we force dynamic contentType since we're
            // rewriting the content - static content will set the header explicitly
            // and fail when it doesn't match
            if (_isHtmlResponse.Value)
                _context.Response.ContentLength = null;

The staticFile middleware has explicitly set the ContentLength and this code sets it to null to effectively let the Response calculate it. This has worked fine in .NET Core 2.x, but in 3.0 I see truncated content. Basically I see a small part of the injected content - basically the length of what otherwise would have been there in the original HTML document.

This bit of code should happen before any content has been written because it is part of the custom stream and fired before each write operation on the stream.

So the question are:

  • Should I be able to reset the Stream length dynamically using the code I have
  • If not what's the right way to Write a different ContentLength?
  • I've also tried explicitly writing out the new calculated content length but that too is ignored

It's possible that

If you want to take a closer look, the runnable sample project is on GitHub, here's the relevant code .

The request in question is the static HTML file link which should get intercepted and injects the script.

Metadata

Metadata

Assignees

Labels

DoneThis issue has been fixedarea-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsbreaking-changeThis issue / pr will introduce a breaking change, when resolved / merged.bugThis issue describes a behavior which is not expected - a bug.feature-kestrel

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions