运行时动态IP限制

运行时动态IP限制

问题描述:

我想在运行时向MVC 5项目添加/删除IP限制。运行时动态IP限制

我做了一个搜索并找到了两种方法。

  1. 在运行时更改动态Ip限制模块。

    using System; 
    using System.Text; 
    using Microsoft.Web.Administration; 
    
    internal static class Sample 
        { 
         private static void Main() 
         { 
          using (ServerManager serverManager = new ServerManager()) 
          { 
          Configuration config = serverManager.GetApplicationHostConfiguration(); 
          ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "Default Web Site"); 
          ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection(); 
    
    
    
        ConfigurationElement addElement = ipSecurityCollection.CreateElement("add"); 
        addElement["ipAddress"] = @"192.168.100.1"; 
        addElement["allowed"] = false; 
        ipSecurityCollection.Add(addElement); 
    
        ConfigurationElement addElement1 = ipSecurityCollection.CreateElement("add"); 
        addElement1["ipAddress"] = @"169.254.0.0"; 
        addElement1["subnetMask"] = @"255.255.0.0"; 
        addElement1["allowed"] = false; 
        ipSecurityCollection.Add(addElement1); 
    
        serverManager.CommitChanges(); 
         } 
         } 
        } 
    

通过这种方式,确实serverManager.CommitChanges重新启动IIS或应用程序?

  1. Best way to implement request throttling in ASP.NET MVC?

  2. 我将使用节流用于此目的。

    如果应用程序或IIS尚未重新启动,我宁愿第一种方式,因为它在IIS级别上。

    你有任何建议哪一个是最好的或任何其他方法?

开始=>

第一种方式重新启动应用程序。第二种方式是在行动层面上工作(已经创建了对象)。

因此,我在Begin_Request上阻止/重定向请求。我添加了要阻止缓存的ips。然后,如果请求ip在黑名单中,我在开始请求时读取缓存值,我将它重定向到404.html。

private void Application_BeginRequest(object sender, EventArgs e) 
    { 
     using (var mylifeTimeScope = IoCBootstrap.Container.BeginLifetimeScope()) 
     { 

      var ipHelper = mylifeTimeScope.Resolve<IIpHelper>(); 
      if (ipHelper.BlackListIp()) 
      { 
       HttpContext.Current.Response.StatusCode = 404; 
       HttpContext.Current.Response.Redirect("404.html"); 
      } 
     } 
    } 

ipHelper.BlackListIp()检查IP在黑名单与否。