在MVC中全局应用动作过滤器,导致重定向循环异常

本文关键字:重定向 循环 异常 过滤器 MVC 全局应用 | 更新日期: 2023-09-27 17:57:33

问题声明:

若会话过期,或者用户试图访问任何视图而不使用剃刀登录MVC 4,我会尝试将用户重定向到登录页面。

  • 如果我使用filter属性的每个操作方法都可以正常工作
  • 我不想将此操作筛选器应用于每个操作方法

我想在全球范围内应用它。如何通过全局应用动作过滤器来避免重定向循环??如何做到这一点??

登录控制器:

//Get Method
public ActionResult Index(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    return View();
}
//Post Method
[HttpPost]
public ActionResult Index(LoginModel loginModel, string returnUrl)
{
    if (ModelState.IsValid)
    {
        objLoginDC.LoginID = loginModel.LoginID;
        objLoginDC.Password = loginModel.Password;
        if (objSvcMasterConfig.IsValid(objLoginDC))
        {
            var varLoginTenantUserDetails = objSvcMasterConfig.GetLoginUserDetails(objLoginDC);
            Session["User"] = varLoginUserDetails[0];
            FormsAuthentication.SetAuthCookie(objLoginDC.LoginID, objLoginDC.RememberMe);
            return RedirectToLogin(returnUrl);
        }
        else
        {
            ModelState.AddModelError("", "The Log In ID or Password provided is incorrect.");
        }
    }
    return View(loginModel);
}

过滤器(动作过滤器):

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CheckUserSessionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpSessionStateBase session = filterContext.HttpContext.Session;
        var user = session["User"];
        if (((user == null) && (!session.IsNewSession)) || (session.IsNewSession))
        {
            session.RemoveAll();
            session.Clear();
            session.Abandon();
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Login" }, { "action", "Index" } });
        }
        base.OnActionExecuting(filterContext);
    }
}

过滤器配置cs:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new Filters.CheckUserSessionAttribute());
    }
}

在MVC中全局应用动作过滤器,导致重定向循环异常

当控制器是Login并且操作是Index时,您可以尝试不执行您的过滤逻辑:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CheckUserSessionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //do not execute the filter logic for Login/Index
        if (filterContext.RouteData.GetRequiredString("controller").Equals("LogIn", StringComparison.CurrentCultureIgnoreCase)
            && filterContext.RouteData.GetRequiredString("action").Equals("Index", StringComparison.CurrentCultureIgnoreCase)){
            return;
        }
        HttpSessionStateBase session = filterContext.HttpContext.Session;
        var user = session["User"];
        if (((user == null) && (!session.IsNewSession)) || (session.IsNewSession))
        {
            session.RemoveAll();
            session.Clear();
            session.Abandon();
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Login" }, { "action", "Index" } });
        }
        base.OnActionExecuting(filterContext);
    }
}