ASP.NET Core Middleware - redirect happens before code for changing headers is executed

47 views Asked by At

I have written a middleware that supposed to cache a specific endpoint redirect (302) and add parameters to it's query string.

This is my middleware code:

public class QueryModifierOnRedirectMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        // Call the next middleware in the pipeline
        await _next(context);
        
        if (context.Request.Path.Value.Equals("/user/pager") &&
            context.Response.StatusCode == 302)
        {
            context.Response.Headers["Location"] = context.Response.Headers["Location"] + "&hello=world";
        }
    }
}

The issue is that the redirect happens before the location is modified. When I debug I see that the location is changed, but while I'm still debugging I see the page in the browser had already been loaded without the extra parameter I'm trying to add.

If I move await _next(); after the if statement than it's debug never hits my breakpoint at location header change.

What am I missing?

0

There are 0 answers