Block IP address in Asp.Net

By Super Man

Block IP address in Asp.Net


In this method, we need two things.



1) A class in App_Code Folder

2) Setting in Web.Config file





1) A class in App_Code Folder

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;



public class IPBlockModule : IHttpModule

{

       public IPBlockModule()

       {

               // TODO: Add constructor logic here

       }

     public void Dispose()

    {

         //Dispose

    }



    public void Init(HttpApplication context)

    {

         context.BeginRequest += new EventHandler(Application_BeginRequest);

    }



    private void Application_BeginRequest(object source, EventArgs e)

    {

       HttpContext context = ((HttpApplication)source).Context;

        string ipAddress = context.Request.UserHostAddress;

        if (IsBlockedIpAddress(ipAddress))

         {

             context.Response.StatusCode = 403;

             context.Response.Write("Forbidden : The server understood the request, but it is refusing to fulfill it.");

        }

    }



    private bool IsBlockedIpAddress(string ipAddress)

    {

         //Here I have stored Ip addresses in String[]. you can also Store in database.

        string[] IPs = {            "117.196.35.121",

                                      "117.196.35.122",

                                      "117.196.35.123",

                                      "117.196.35.124",

                                      "127.0.0.1"

                       };



        foreach(string IP in IPs)

        {

            if(IP == ipAddress)

                 return true;

        }

         return false;

  

    }

    

}





In the Application_beginRequest, we check that the IP address is Blocked or not? If User IP Address is blocked then User can not view the page.



In this method IsBlockedIpAddress you can verify that it is valid IP address or blocked, Here I have store blocked address in the String array but you can also store in database.

You can also write here your custom checking.



2) Setting in Web.Config file



Now
, we add this HTTP Module in web.config file so that we can use it.

<configuration>

       <system.web>

              <compilation debug="true" targetFramework="4.0"/>

              <httpModules>

                     <add name="IPBlockModule" type="IPBlockModule"/>

              </httpModules>

       </system.web>

</configuration>


Block IP address in Asp.Net  (1538 Views)