Asp.net Mvc: List all the actions on a controller with specific attribute

老子叫甜甜 提交于 2019-11-30 03:48:18

问题


I am trying to list all the controllers and their actions with specific attributes to create a dynamic google sitemap. So that I can "mark" certain actions with an attribute so they show up in the sitemap.

Here I found out how to get all the controllers. But I am not sure how to get all their Actions with a particular attribute. I tried GetMethods and then use GetCustomAttributes but I am not sure if that's the right way to do it. It felt a little over complicated.

Once I get the controllers and their actions I was going to use the technique explained here to get the urls. As you may notice Eric Duncan talks about what I am trying to accomplish in that question.

Thanks in advance.


回答1:


I use some code in my unit tests to verify that certain actions are decorated with attributes. It uses reflection with some enumerable extension method goodness. I think you could adapt this. Note, if you only care about whether it exists or not, you could use Count() on the enumeration rather than getting the actual attribute. This way allows you some flexibility in using attribute properties to customize the behavior. Using the inheritance tree would allow you to decorate an entire controller.

 var methods= controller.GetType()
                        .GetMethods( BindingFlags.Public | BindingFlags.Instance )
 foreach (var info in methods)
 {
     if (info.ReturnType  == typeof(ActionResult))
     {
        var attribute = info.GetCustomAttributes( typeof( SiteMapAttribute ), true )
                            .Cast<SiteMapAttribute>()
                            .FirstOrDefault();

        if (attribute != null && !attribute.Exclude.Contains( info.Name ))
        {
            ...
        }
    }
}


来源:https://stackoverflow.com/questions/1358170/asp-net-mvc-list-all-the-actions-on-a-controller-with-specific-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!