开发者

How can I get MVC action information from the action's MethodInfo?

开发者 https://www.devze.com 2023-01-15 22:43 出处:网络
As my application initializes, I want to create a registry of any M开发者_C百科VC action whose method has a certain CustomAttribute on it. I want this registry to keep track of the MVC Area, Controlle

As my application initializes, I want to create a registry of any M开发者_C百科VC action whose method has a certain CustomAttribute on it. I want this registry to keep track of the MVC Area, Controller, and Action. I could require the person adding the attribute to specify this information, but it seems like I should be able to figure out this information based on the MethodInfo: basically the reverse of what happens when the ActionLink method is called. How can I do this?


Search through the assembly for every Controller, then search through all the methods to find those with a certain attribute on them.

// current assembly -> all types that have basetype controller -> grab methods
foreach(var type in System.Reflection.Assembly.GetCallingAssembly().GetTypes().Where(t=>
    typeof(Controller).IsAssignableFrom(t))))
{
    foreach(var methodInfo in type.GetMethods())
    {
        if (methodInfo.GetCustomAttributes(typeof(MyAttribute), false).Count() > 0)
        {
            var action = methodInfo.Name;
            var controller = type.Name;
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消