重定向所有动作控制器

时间:2014-01-08 16:34:22

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

只有一个控制之家带有一堆动作。它还有一个私有方法bool IsFinish(),它返回系统的状态。在某个阶段(即当IsFinish开始返回 true 时)是必要的,任何可调用的方法都重定向到公共ActionResult Result()。原则上,我不关心这会导致什么 - 在当前的控制器或其他控制器。概述所有行动。

如何实施?

1 个答案:

答案 0 :(得分:5)

您可以使用action filter的asp.net mvc来执行此操作。操作过滤器是一种属性,您可以将其应用于controller action - 或整个controller - 修改执行操作的方式,对于示例:

public class RedirectFilterAttribute : ActionFilterAttribute
{
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // get the home controller in a safe cast
            var homeController = filterContext.Controller as Controller;

            // check if it is home controller and not Result action
            if (homeController != null && filterContext.ActionDescriptor.ActionName != "Result")
            {
                if (homeController.IsFinish())
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary 
                        { 
                            { "controller", "Home" }, 
                            { "action", "Result" } 
                        });
                }
            }

            base.OnActionExecuting(filterContext);
        }
}

并将其应用于您的控制器:

[RedirectFilter] // apply to all actions
public class HomeController : Controller
{

    public ActionResult Home()
    {
        /* your action's code */
    }

    public ActionResult Home()
    {
        /* your action's code */
    }

    public ActionResult Home()
    {
        /* your action's code */
    }

    public ActionResult Result()
    {        
        return View();
    }
}