c# – Application_BeginRequest用法

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

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吗?

最佳答案
您可以使用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

转载注明原文:c# – Application_BeginRequest用法 - 代码日志