OnActionExecuting Loop MVC

本文关键字:MVC Loop OnActionExecuting | 更新日期: 2023-09-27 18:04:33

我使用动作过滤器在我的项目做一个工作。我想这样做,如果user的ip等于我的ip,它会去index,而不会看到登录页面。如果它的ip是不同的,我想把他重定向到登录页面。在登录页面我问密码和id。我有一个重定向到登录页面的问题。这是我的代码,我怎么能修复这个循环?

<标题>过滤器h1> 登录控制器
public class LoginController : Controller
{
    // GET: Login
    [IntranetAction]
    public ActionResult User()
    {         
        return View();
    }

    public void checkAuthentication(UserLoginInfo loginInfo)
    {         
        bool isAuthenticated = new LdapServiceManager().isAuthenticated(loginInfo);
        if (isAuthenticated)
        {
            //HttpContext.Response.Redirect("/Home/Index");
            Response.Redirect("/Home/Index");
            Response.End();
        }
        else
        {
            Response.Redirect("/", false);
        }         
    }
}

过滤器类中的这个循环。shortLocalIP不等于LOCALIP,它会转到登录页面但它会转到inf loop

OnActionExecuting Loop MVC

我认为你需要在登录控制器中另一个视图Index

如果user ipyour ip相等,则转到Home/Index,否则转到Login/Index

您的startup视图将是Login/User,您的filter将被放置。

public class IntranetAction : ActionFilterAttribute
{
    private const string LOCALIP = "192.168";
    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)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "Login", //TODO - Edit as per you controller and action
                action = "Index"
            }));
        }
        else
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "Home", //TODO - Edit as per you controller and action
                action = "Index"
            }));
        }
        base.OnActionExecuting(filterContext);
    }
}