Asp. net Core How to Set Black and White List of Routing Restrictions

  • 2021-12-04 09:50:15
  • OfStack

In the original AspnetMvc, we will use routing access restrictions, and write the following in AppStart/RouteConfig. cs:


routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

But in aspnet core mvc, there is no RouteConfig. cs and this writing. How can we achieve the same effect in Aspnet core mvc?

Here we need to use the middleware when UrlFirewall

1) Description:

UrlFirewall is an open source, lightweight middleware for filtering http requests, which can be used in webapi or gateway

2) Introduction:

UrlFirewall is a request filtering middleware of http, which can be matched with gateway (Ocelot) to shield external network from accessing internal interfaces, and only let internal interfaces communicate with each other without exposing to the outside. It supports blacklist mode and whitelist mode, and supports custom http request response code. It has good expansibility, and can realize verification logic by itself, and retrieve rules from database or Redis cache and other media

3) Use:

1], add components from Nuget to your ASP. NET Core project


Install-Package UrlFirewall.AspNetCore

2], configure DI on startup. cs's ConfigureServices


services.AddUrlFirewall(options =>
            {
                options.RuleType = UrlFirewallRuleType.Black;
                options.SetRuleList(Configuration.GetSection("UrlBlackList"));
                options.StatusCode = HttpStatusCode.NotFound;
            });

3], configure middleware Configure in startup. cs


app.UseUrlFirewall();// Enable the firewall   Open blacklist request path 
if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //HttpContext
                app.UseStaticHttpContext();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

4], Configuration. GetSection ("UrlBlackList") in Root 2 requires the following configuration to be added to the Section name used. UrlBlackList. We added to the file appsettings. json/appsettings. Devolopment. json


{
"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  // The firewall filters this type of access 
  "UrlBlackList": [
    {
      "Url": "{resource}.axd/{*pathInfo}",
      "Method": "All"
    }
  ]
}

In this way, the. axd on our server will not be requested to


Related articles: