Skip to main content

Restrict ip,user agent,crawlers in asp.net global.asax


Introduction:
In this article I am going to explain about how to allow or restrict particular ips and user agents and crawlers in global.asax file in asp.net/c#.net.

Explanation:
Some internal applications which is used only by particular organization or required to restrict other ips other than their office ips. And also we may restrict the search engines and other crawlers from our competitive sites. For the explanation purpose I have a xml called whitlist.xml which contains all the ip addresses which is to be allowed and user agents which is to be allowed. And important point to know is crawlwers won’t have the cookie for that session. Below is the xml file format.

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <whitelistip ip=""/>
  <whitelistip ip=""/>
  <whitelistip ip=""/>
  <whitelistagent agent="yahoobot" />
  <whitelistagent agent="googlebot" />
</root>

Steps:
I have added all the white listed ips in iplist arraylist and all the allowed useragents to agentlist arraylist. I am checking whether the requesting ip has cookie. If it has ip then it is valid request else it is from a crawler. I am redirecting the session less request to access denied page. All this request is available only in Application_AcquireRequestState . That’s why I am writing all the logics in Application_AcquireRequestState.

Below is the code

void Application_AcquireRequestState(object source, EventArgs e)
    {
       
        try
        {
            LoadWhitelist();
            //checks whether the ip is whitelisted ip or whitelisted agent
            if (CheckIP(Request.UserHostAddress.ToString()) || CheckUserAgent(Request.UserAgent.ToString()))
            {
                return;
            }
            else if (!Session.IsCookieless)// checks user request has cookie
            {
                RedirectPage();
                return;
            }
            else
            {
                RedirectPage();// redirect the page to access denied page.
            }
        }
        catch (Exception ex)
        {

        }
    }
    private void RedirectPage()
    {
        if (Session["redirect"] + "" != "")
        {
            if (Session["redirect"] + "" == "true")
            {
                Session["redirect"] = "false";
                return;
            }
        }
        else
        {
            Session["redirect"] = "true";
            Session["nexturl"] = HttpContext.Current.Request.Url.AbsoluteUri;
            Response.Redirect("accessdenied.aspx", false);
        }
    }
    private void LoadWhitelist()
    {
        if (System.Configuration.ConfigurationManager.AppSettings["whitelist"] + "" != "")
        {
            string path = System.Configuration.ConfigurationManager.AppSettings["whitelist"].ToString();
            if (System.IO.File.Exists(path ))
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(path );
                XmlElement xEle;
                if (xDoc != null)
                {
                    foreach (XmlNode xNode in xDoc.DocumentElement.SelectNodes("//whitelistip"))
                    {
                        xEle = (XmlElement)xNode;
                        iplist.Add(xEle.GetAttribute("ip").ToString());
                    }
                    foreach (XmlNode xNode in xDoc.DocumentElement.SelectNodes("//whitelistagent"))
                    {
                        xEle = (XmlElement)xNode;
                        agentlist.Add(xEle.GetAttribute("agent").ToString());
                    }
                }
            }
        }
    }
    public Boolean CheckIP(string userip)
    {
        if (iplist.Contains(userip))
            return true;
        else
            return false;
    }
    public Boolean CheckUserAgent(string useragent)
    {
        foreach (string s in agentlist)
        {
            if (useragent.Contains(s))
                return true;
        }
        return false;
    }


If you have any doubt please enter it in comments.Complete source code is attached below. 


Comments

Post a Comment

Popular posts from this blog

Code to create log files in C#.Net|Asp.Net

Introduction: In my previous article I have explained about how to create, delete and check whether the directory exists using C#.Net . In this article I am going to explain about  How to create log files in C#.Net. Explanation: Log files are useful to track any runtime errors and exceptions in all the applications. Below code will code will get the Message and Pagename as the input and creates the log file in that date. For that first i have imported below two namespaces.

Dynamically programmatically add contols at run time Asp.Net

Introduction: In my previous article I have explained about What is View State? How to Store and retrieve values from View State . In this article I am going to explain how to add controls programmatically on run time. Explanation: This example adds a text box and button to a Web Forms page at run time. It also dynamically binds an event handler to the button's   Click   event. The handler displays the values of the dynamically generated text box. The controls are added into a   Panel   Web server control, which acts as a placeholder. The controls are separated in the panel with line breaks (HTML <BR> elements), which are added to the panel using the   LiteralControl   control.

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     { ...