FilterContext for ActionResult in the OnResultExecuted ASP.NET MVC method

I need to filter only methods from all actions that return the ActionResult type from controller actions. I get the name of the controller and the name of the action from the following.

string originController = filterContext.RouteData.Values["controller"].ToString(); string originAction = filterContext.RouteData.Values["action"].ToString(); 

but how can I only filter a method that has an ActionResult return type?

+7
asp.net-mvc
source share
2 answers

Try this type of code to access controllers, actions, and

  string originController = filterContext.RouteData.Values["controller"].ToString(); string originAction = filterContext.RouteData.Values["action"].ToString(); string originArea = String.Empty; if (filterContext.RouteData.DataTokens.ContainsKey("area")) originArea = filterContext.RouteData.DataTokens["area"].ToString(); 
+9
source share

Try this in Action Filter :

 var controllerActionDescriptor = filterContext.ActionDescriptor as System.Web.Mvc.ReflectedActionDescriptor; if (controllerActionDescriptor == null || controllerActionDescriptor.MethodInfo.ReturnType != typeof(ActionResult)) { return; } // if we got here then Action return type is 'ActionResult' 

Update:

Since you are using the OnResultExecuted method, try the following:

 public override void OnResultExecuted(ResultExecutedContext filterContext) { string originController = filterContext.RouteData.Values["controller"].ToString(); string originAction = filterContext.RouteData.Values["action"].ToString(); var actionType = filterContext.Controller.GetType().GetMethod(originAction).ReturnType; if (actionType != typeof(ActionResult)) return; // if we got here then Action return type is 'ActionResult' } 

Update:

According to your comment, if there is more than one Action with the same name (overload):

 public override void OnResultExecuted(ResultExecutedContext filterContext) { var actionName = filterContext.RouteData.Values["action"].ToString(); var ctlr = filterContext.Controller as Controller; if (ctlr == null) return; var invoker = ctlr.ActionInvoker as ControllerActionInvoker; if (invoker == null) return; var invokerType = invoker.GetType(); var getCtlrDescMethod = invokerType.GetMethod("GetControllerDescriptor", BindingFlags.NonPublic | BindingFlags.Instance); var ctlrDesc = getCtlrDescMethod.Invoke(invoker, new object[] {ctlr.ControllerContext}) as ControllerDescriptor; var findActionMethod = invokerType.GetMethod("FindAction", BindingFlags.NonPublic | BindingFlags.Instance); var actionDesc = findActionMethod.Invoke(invoker, new object[] { ctlr.ControllerContext, ctlrDesc, actionName }) as ReflectedActionDescriptor; if (actionDesc == null) return; if (actionDesc.MethodInfo.ReturnType == typeof (ActionResult)) { // you're in } } 
+5
source share

All Articles