在HttpModule中执行执行操作

Eri*_*röm 10 asp.net-mvc

我有一个HttpModule,需要知道正在执行哪个操作.而且我需要从方法中获取MethodInfo,动作名称是不够的,我需要从类型的真实方法.

我知道如何获得控制器和动作:

string controllerName = ...RouteData.Values["controller"].ToString();
string actionName = ...RouteData.Values["action"].ToString();
Run Code Online (Sandbox Code Playgroud)

我想要做:
controllerType.GetMethod(actionName)

这当然会导致AmbiguousMatchException ...

哪个签名正在执行?有可能知道吗?

jef*_*non 0

这应该有效。它循环遍历路线数据并获取所有不为人所知的路线数据,即控制器、操作和区域。这是假设您使用默认路由。路由的所有其他部分,无论是在 URL 还是查询字符串中,都将映射到方法参数。您可以获取这些路由值的 Type 并使用它们来获取指定的 Method 信息。

List<Type> methodParams = new List<Type>();
string action = HttpContext.Current.Request.RequestContext.RouteData["action"];
foreach (var data in HttpContext.Current.Request.RequestContext.RouteData.Values)
{
    if ((data.Key != "action") && (data.Key != "controller") && (data.Key != "area"))
        methodParams.Add(data.Value.GetType());                
}

Type t; //assume this is your type that implements the action method you're interested in.  
        //I'm assuming you know it somehow

MethodInfo info = t.GetMethod(action, methodParams.ToArray());
Run Code Online (Sandbox Code Playgroud)