简体   繁体   中英

Application_BeginRequest Usage

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

GLOBAL.ASAX

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

        string ip1 = request.UserHostAddress;
        string shortLocalIP;
        if (ip1 != null && 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();       
        }
    }

LOGIN CONTROLLER

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

LOGIN CSHTML

 <form class="login-form" action="/Login/checkAuthentication" method="post" novalidate="novalidate">

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

Should we use SESSION START in GLOBAL.ASAX??

You can use ActionFilter for this. Create a class for custom filter, something like this -

public class IntranetAction : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool isIPAddressValid = false;//TODO: Check the IP validity here
        if (isIPAddressValid)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "Account", //TODO - Edit as per you controller
                action = "Login"        //and Action
            }));
        }

        base.OnActionExecuting(filterContext);
    }
}

And simply use it over your controller ActionMethod like this for example -

    [IntranetAction]
    public ActionResult Index()
    {
        return View();
    }

Suugest to go through a good article to get started with custom filters - http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs

Application_BeginRequest will be called on every request made to your server. If you want to execute some logic only on certain action use ActionFilters

You can use ActionFilter for MVC. Here is the sample code for the operation.

public class IpControlAttribute : ActionFilterAttribute {
    private const string LOCALIP = "";

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        var request = filterContext.RequestContext.HttpContext.Request;

        string ip1 = request.UserHostAddress;
        string shortLocalIP;
        if (ip1 != null && 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;
            }

            filterContext.Result = new RedirectResult("/Account/Login");
        }
    }
}

Then you need to add it as global filter in FilterConfig.cs

filters.Add(new IpCheckAttribute());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM