【问题标题】:Redirect for all action controller's重定向所有动作控制器
【发布时间】:2014-01-09 00:48:01
【问题描述】:

只有一个控件 Home 有一堆动作。它还有一个私有方法 bool IsFinish(),它返回系统的状态。在某个阶段(即IsFinish开始返回true时)是必要的,任何可调用的方法重定向到public ActionResult Result()。原则上,我不在乎这会在哪里导致 - 在当前控制器或其他控制器中。概述对其进行的所有操作。

如何实现?

【问题讨论】:

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


    【解决方案1】:

    您可以使用 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-28
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多