How To Block IP Addresses from your website using ASP.NET

To block an IP address from your web application we used a HttpModule that could be reused in any ASP.NET application. When an IP address is blocked it stops the response and sends a “403 Forbidden” header. Even though it’s almost impossible to block someone from accessing your website, this is a simple way to make it much harder to do. For the regular web users, this is probably enough to keep them out. IpBlockingModule.cs

using System;
using System.Web;
using System.Configuration;
using System.Collections.Specialized;

///
/// Block the response to certain IP addresses
///
public class IpBlockingModule : IHttpModule
{


    void IHttpModule.Dispose()
    {
        // Nothing to dispose;
    }

    void IHttpModule.Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    ///
    /// Checks the requesting IP address in the collection
    /// and block the response if it's on the list.
    ///
    private void context_BeginRequest(object sender, EventArgs e)
    {
        string ip = HttpContext.Current.Request.UserHostAddress;
        if (_IpAdresses.Contains(ip))
        {
            HttpContext.Current.Response.StatusCode = 403;
            HttpContext.Current.Response.End();
        }
    }

    private static StringCollection _IpAdresses = FillBlockedIps();

    ///
    /// Retrieves the IP addresses from the web.config
    /// and adds them to a StringCollection.
    ///
    /// A StringCollection of IP addresses.
    private static StringCollection FillBlockedIps()
    {
        StringCollection col = new StringCollection();

        string raw = ConfigurationManager.AppSettings.Get("blockip");
        raw = raw.Replace(",", ";");
        raw = raw.Replace(" ", ";");

        foreach (string ip in raw.Split(';'))
        {
            col.Add(ip.Trim());
        }

        return col;
    }

}

Implementation Add IpBlockingModule.cs to the App_Code folder. Then add the following line to the <system.web> section of the web.config.

 <httpModules>
    <add type = "IpBlockingModule" name= "IpBlockingModule" />
  </httpModules>

Then add the IP addresses you want to block, separated by commas, to the appSettings on the web. config.

  <appSettings>
    <add key = "blockip" value = "44.0.234.122, 23.4.9.231"/>
  </appSettings>

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru