Application_BeginRequest用法

时间:2016-08-26 07:01:15

标签: c# asp.net asp.net-mvc

我们正在ASP.NET MVC项目中尝试一些登录操作。我们的目标是:“如果用户的IP不是来自我们的内部网,请将他/她重定向到登录页面。否则,只需转到我们的索引页面。我们写了一些代码,但我们在循环中。< / p>

的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();       
        }
    }

登录控制器

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

登录CSHTML

 <form class="login-form" action="/Login/checkAuthentication" method="post" novalidate="novalidate">
每当我们按某个按钮或其他按钮时,每次都会触发Application_BeginRequest。但我们只想在开始时进行这些操作。感谢...

我们是否应该在GLOBAL.ASAX中使用SESSION START

3 个答案:

答案 0 :(得分:4)

您可以使用ActionFilter。为自定义过滤器创建一个类,如下所示 -

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

只需在您的控制器ActionMethod上使用它,例如 -

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

Suugest通过一篇好文章来开始使用自定义过滤器 - http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs

答案 1 :(得分:1)

每次向您的服务器发出请求时都会调用Application_BeginRequest。如果您只想对某些操作执行某些逻辑,请使用ActionFilters

答案 2 :(得分:1)

您可以将 ActionFilter 用于MVC。以下是操作的示例代码。

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

然后您需要在 FilterConfig.cs

中将其添加为全局过滤器
filters.Add(new IpCheckAttribute());