重定向所有动作控制器

-1 c# asp.net-mvc razor asp.net-mvc-4

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

如何实施?

Fel*_*ani 5

您可以使用action filterasp.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);
        }
}
Run Code Online (Sandbox Code Playgroud)

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

[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();
    }
}
Run Code Online (Sandbox Code Playgroud)