Run middleware just before output is sent to the b...
# help-with-umbraco
s
I'm trying to add some middleware to search and replace specific things in the html output of a page. I've made the middleware for this, but I can't figure out how to register it correctly. I've tried registering like mentioned in https://docs.umbraco.com/umbraco-cms/reference/routing/custom-middleware using the PostPipeline. But when I debug things, the middleware is hit before my controller endpoint is hit. Is there some way I can change the order?
m
for CSP Manager I am doing:
Copy code
builder.Services.Configure<UmbracoPipelineOptions>(options =>
        {
#if NET8_0_OR_GREATER
            options.AddFilter(new UmbracoPipelineFilter(
                CspConstants.PackageAlias,
                postPipeline: applicationBuilder =>
                {
                    applicationBuilder.UseMiddleware<CspMiddleware>();
                }));
        });
#else
            options.AddFilter(new UmbracoPipelineFilter(
                CspConstants.PackageAlias,
                _ => { },
                applicationBuilder =>
                {
                    applicationBuilder.UseMiddleware<CspMiddleware>();
                },
                _ => { }));
        });
#endif
This also includes adding a value that is only called from Razor files so I assume its happening after page "rendering"
d
There is also an event on the HttpContext that you can hook into that gets fired right before the response is sent to the client. I'm on my phone right now, but it's something similar to :`httpContext.OnBeforeSendingHeaders`
s
Must have had something wrong in my middleware, reworked it a bit, and now it works 🙂
although it get's hit twice, but I can live with that
n
@skttl Middleware get's hit in both directions of the ASP.Net Core pipeline, to know whether your on the inbound request or the outbound response you should hook into the
context.Response
event bits I believe inside the InvokeAsync method.. something a bit like this:
Copy code
cs
 context.Response.OnStarting(async () =>
        {
           //maniuplate response here - but watch out for things like content length headers ending up incorrect
}
(https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/request-response?view=aspnetcore-8.0#startasync might help with that.)
r
You can use PostPipeline, or UseUmbraco().WithMiddleware(.. ADD YOUR MIDDLEWARE HERE), but also just the regular UseMiddleware methods.
m
This one is golden, for avoiding the
System.InvalidOperationException: The response headers cannot be modified because the response has already started.
have already been sent!
170 Views