8

コントローラー アクションからの戻り型 ActionResult を持つすべてのアクションからメソッドのみをフィルター処理する必要があります。以下からコントローラー名とアクション名を取得しています。

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

しかし、戻り値の型 ActionResult を持つメソッドのみをフィルタリングするにはどうすればよいですか?

4

2 に答える 2

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();
于 2013-11-07T12:58:13.493 に答える
7

あなたのでこれを試してください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
    }
}
于 2013-07-26T10:34:07.187 に答える