Is there a way to reinstall all controllers / actions on an ASP.NET MVC3 site?

I am trying to make a dynamic menu function on an ASP.NET MVC 3 website - and I would like to know if there is a built-in way to get all the controllers and actions at runtime?

I understand that I can use reflection to find all the public methods on my controllers, but that does not give me the relative URL that should be placed in the <a href="..."> tag.

In addition, I'm going to decorate some of the β€œactions” with filter attributes that determine whether the current user can see / go to these pages. Therefore, it would be better if I had access to filters in order to be able to call the IsAccessGranted() method.

What are my options? What is the best option?

+4
source share
3 answers

MVC has no built-in mechanism for listing all of your controllers and actions. You will need to use reflection to check all loaded types and see their methods and their associated attributes. Of course, it is assumed that you are using the default action dispatch mechanism. Because the MVC pipeline can be replaced in several places, it is easy to implement a system to invoke action methods that are not based on CLR classes and methods. But if you have full control over your application, it’s easier for you.

+1
source

I just did it two weeks ago.

 var q = from type in Assembly.GetExecutingAssembly().GetTypes() where type.IsClass && type.Namespace != null && type.Namespace.Contains("Controller") select type; q.ToList().ForEach(type => doWhatYouNeedToDo(type))); 

if you use T4MVC then this script will return double entries. To avoid this, work with

 && !type.Name.Contains("T4MVC") 

In the doWhatYouNeedToDo () method, you can convert the Type object to a DTO that suits your needs and add extra work to it.

As for your dynamic menu, you can use MvcSiteMapProvider and implement your own dynamic sitemapprovider with it, so that you are no longer attached to the xml file of the static Sitemap.

But in .NET, reflection is pretty slow, so you might want to keep the views of your controllers and method in a database.

+3
source

Try TVMVC . You still have to use reflection, but t4 templates will generate a class that is easier to iterate over.

0
source

All Articles