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

前端 未结 1 739
失恋的感觉
失恋的感觉 2021-01-05 01:56

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 attribu

相关标签:
1条回答
  • 2021-01-05 02:31

    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 ))
            {
                ...
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题