Search code examples
c#.net.net-coreasp.net-core-2.1

Why is Custom Middleware Still Being Run?


Platform

.Net Core 2.2 Web App

Scenario

I wrote some custom middleware with the intent to be executed only when my request path matches a specified location. When it runs, it does a lookup from a database and checks a piece of data. Under certain circumstances, the middleware will redirect the user to a new url instead of letting them view the requested one.

Problem

The middleware seems to be cached or something. I don't understand it. When I request localhost:6000/url-that-should-work, I'm magically getting the wrong page at a different url. However when I use Fiddler, it's not a redirect. It's like that's the page that I actually requested. The weird part is that a) I have my middleware code commented out in Startup.cs and b) when I go into incognito mode, the behavior works as expected. Also, if I change the debug port to something different, it works as well. Also, when I put a breakpoint in my middleware, if I go to /url-that-should-work, the request path is the wrong url.

Code

Startup.cs

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();

//app.UseEndpointRouting();
//app.UseWhen(context => context.Request.Path.StartsWithSegments("/move/booking"), appBuilder =>
//{
//    appBuilder.UseMoveBookingWorkflowPermission();
//});

app.UseMvc();

Middleware redirect line that should not be executing

context.Response.Redirect(context.Request.PathBase + previousPath + context.Request.QueryString, true);

Solution

  • This is one of those "I'm stupid" moments. The issue was that when I was redirecting the response, I was specifying that I wanted it to be permanent.

    Old

    context.Response.Redirect(context.Request.PathBase + previousPath + context.Request.QueryString, true);
    

    New

    context.Response.Redirect(context.Request.PathBase + previousPath + context.Request.QueryString, false);