OnActionExecuting 中的重定向不起作用

mau*_*lla 1 c# asp.net-mvc asp.net-mvc-4

我正在尝试重定向未通过 OnactionExecuting() 进行身份验证的访问者,以便它覆盖我的整个控制器,但它几乎就像被完全跳过一样。是否可以从 OnActionExecuting() 内重定向?

  protected override void OnActionExecuting(ActionExecutingContext filterContext)
{

    base.OnActionExecuting(filterContext);
    if (SimpleAuth.isAuth())
    {
        RedirectToAction("Login", "Users");
    }
}
Run Code Online (Sandbox Code Playgroud)

Far*_*yev 5

您不能使用RedirectToAction内部过滤器。RedirectToActionController班级的成员。这就是为什么您可以在操作方法中调用此方法的原因,这些方法是从Controller类继承的类的成员。

但是,如果我们谈论过滤器,那么您必须设置filterContext.Result为一个新的RedirectToRouteResult

 filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
                                new
                                {
                                    controller = "Users",
                                    action = "Login"
                                }));
Run Code Online (Sandbox Code Playgroud)