c#

ASP.NET Core: How to restrict specific routes from middleware.

As a web developer, it is essential to understand how to restrict specific routes in asp.net core so that middleware can run successfully. Middleware is a function that can be added to a route to perform operations such as authentication, logging, or input validation before the request is passed to the handler function.

Knowing which routes require middleware’s functionality is essential when creating it. For example, if a route requires logging, you would want to restrict middleware to run only on that route.

To restrict middleware to specific routes, use the `builder.UseWhen()` method, which mounts middleware functions at a particular path. The `builder.UseWhen()` method takes two parameters: the predicate and the  Predicate , Action<IApplicationBuilder>

Here is an example of how to restrict middleware to a specific route:

Extension method:

public static IApplicationBuilder RestrictRoute(this IApplicationBuilder builder, string[] routes)
        {
            if (routes.Count() > 0)
            {
                builder.UseWhen(context => !routes.Any(a => context.Request.Path.StartsWithSegments(a)), builder =>
                {
		   //Logging middleware
                    builder.UseRequestLogging();
                });
            }
            return builder;
        }

In the example above, the UseRequestLogging function does not apply to the route passed to the extension method. When the URL is requested, the middleware function is not executed for the routes the URL passed to this extension method.

In the programs.cs file

var restrictEndPoints= builder.Configuration.GetSection("RestrictEndPoints").Get<string[]>();

app.RestrictRoute(restrictedEndpoints ?? Array.Empty<string>());

In the Appsettings.json file:


{
  "RestrictEndPoints": 
[ 
 "/api/GetActiveMessage", 
 "/api/GetActiveQuestions", 
 "/api/GetActiveAnwsers"
 ]
}

builder.When () can ensure your application conditionally allows or restricts specific routes. This example helps keep the middleware running on particular routes.