ASP.NET MVC的OnResultExecuted方法中的ActionResult的filterContext

时间:2013-07-25 08:06:59

标签: asp.net asp.net-mvc

我只需要从控制器操作中返回所有具有返回类型ActionResult的操作中的方法。 我从以下获取控制器名称和操作名称..

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

但是我怎样才能只过滤返回类型为ActionResult的方法?

2 个答案:

答案 0 :(得分:9)

尝试使用此类代码访问控制器,操作以及

  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();

答案 1 :(得分:6)

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's return type is 'ActionResult'

<强>更新

由于您使用OnResultExecuted方法,请尝试以下操作:

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's return type is 'ActionResult'
}

<强>更新

根据您的评论,如果有多个Action具有相同的名称(重载):

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
    }
}