asp.net-mvciisdynamic-ip

Dynamic Ip Restriction on Runtime


I want to add/remove IP restriction on run time to a MVC 5 project.

I did a search and found two ways.

  1. Change Dynamic Ip Restriction module on runtime.

    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();
             }
           }
         }
    

In this way, does serverManager.CommitChanges restart the IIS or application ?

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

I will use throttling for this purpose.

If the application or IIS hasn't been restarted, I would prefer first way because it's on IIS level.

Do you have any suggestion which one is the best or any other approaches ?


Solution

  • First way restarts the application. Second way is working on action level (objects are created already).

    Therefore, I'm blocking/redirecting request on Begin_Request. I'm adding ips which I want to block to cache. Then I'm reading cache value on begin request if request ip is in blacklist I'm redirecting it to 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() checks ip is in blacklist or not.