How to skip action execution from an ActionFilter?

前端 未结 4 579
轮回少年
轮回少年 2020-12-09 01:10

Is it possible to skip the whole action method execution and return a specific ActionResult when a certain condition is met in OnActionExecuting?

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 01:49

    See my download sample and MSDN article Filtering in ASP.NET MVC.

    You can cancel filter execution in the OnActionExecuting and OnResultExecuting methods by setting the Result property to a non-null value.

    Any pending OnActionExecuted and OnActionExecuting filters will not be invoked and the invoker will not call the OnActionExecuted method for the cancelled filter or for pending filters.

    The OnActionExecuted filter for previously run filters will run. All of the OnResultExecutingand OnResultExecuted filters will run.

    The following code from the sample shows how to return a specific ActionResult when a certain condition is met in OnActionExecuting:

    if (filterContext.RouteData.Values.ContainsValue("Cancel")) 
    {
        filterContext.Result = new RedirectResult("~/Home/Index");
        Trace.WriteLine(" Redirecting from Simple filter to /Home/Index");
    }
    

提交回复
热议问题