Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a route is valid in a .NET Core middleware before UseEndpoints does?

I am using .NET Core 3.1, creating a web api.

My API Controllers are being mapped with the following:

app.UseEndpoints(endpoints => endpoints.MapControllers());

Is there a way that I can perform an action only if a route matches, but before the actual controller action is executed?

I'm in a situation where I need to create an entity in the database before the application logic is executed.

I initially considered a custom middleware, but only to realise that if I place the middleware before app.UseEndpoints it would fire for any and all requests (lots of dummy entities would be created), even those that don't route.

If I place it after app.UseEndpoints it's too late as the application code will have already executed.

Managing a white list of routes in a middleware that runs before app.UseEndpoints was a thought, but would be a maintenance hassle.

So is there a way to hook into the endpoint routing, or an API in the framework that can let me "preemptively" determine if a route is valid?

like image 553
Chris Avatar asked Sep 05 '25 03:09

Chris


1 Answers

The call to UseRouting does the job of figuring out which endpoint is going to run. If a match is found, it sets the Endpoint for the current HttpContext. This is available inside a middleware component using HttpContext.GetEndpoint. Here's an example that uses this approach:

app.UseRouting();

app.Use(async (ctx, next) =>
{
    // using Microsoft.AspNetCore.Http;
    var endpoint = ctx.GetEndpoint();

    if (endpoint != null)
    {
        // An endpoint was matched.
        // ...
    }

    await next();
});

app.UseEndpoints(endpoints => endpoints.MapControllers());
like image 177
Kirk Larkin Avatar answered Sep 07 '25 21:09

Kirk Larkin