Application_BeginRequest Usage
<p>we are trying some login operations in our ASP.NET MVC project. Our goal is : "<strong>If user's IP is not from our intranet, redirect him/her to login page. Else, just go to our index page</strong>. We wrote some code but we are inside a loop. </p>

<h1>GLOBAL.ASAX</h1>

<pre><code>protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var request = ((System.Web.HttpApplication) sender).Request;

        string ip1 = request.UserHostAddress;
        string shortLocalIP;
        if (ip1 != null &amp;&amp; ip1.Contains("."))
        {
            string[] ipValues = ip1.Split('.');
            shortLocalIP = ipValues[0] +"."+ipValues[1];
        }
        else
        {
            shortLocalIP = "192.168";
        }

        //var ip2 = request.ServerVariables["LOCAL_ADDR"];
        //var ip3 = request.ServerVariables["SERVER_ADDR"];

        if (shortLocalIP != LOCALIP)
        {
            if ("/Login/User".Equals(request.RawUrl, StringComparison.InvariantCultureIgnoreCase))
            {                   
                    return;                                  
            }

            Response.Clear();            
            Response.Redirect("/Login/User");             
            Response.End();       
        }
    }
</code></pre>

<h1>LOGIN CONTROLLER</h1>

<pre><code> public class LoginController : Controller
{
    // GET: Login
    public ActionResult User()
    {         
        return View();
    }

    public ActionResult checkAuthentication(FormCollection collection)
    {
        bool isAuthenticated = new LdapServiceManager().isAuthenticated(collection);
        if (isAuthenticated)
        {
            Response.Redirect("Home/Index");
        }
        else
        {
            Response.Redirect("/Login/User");
        }
        return null;
    }
}
</code></pre>

<h1>LOGIN CSHTML</h1>

<pre><code> &lt;form class="login-form" action="/Login/checkAuthentication" method="post" novalidate="novalidate"&gt;
</code></pre>

<p>Application_BeginRequest triggers everytime when we press some button or something else. But we want these operations at the beginning only. Thanks...</p>

<p><strong>Should we use SESSION START in GLOBAL.ASAX??</strong></p>