willem
willem

Reputation: 27027

Is there a way to get the Controller Type through the ASP.NET MVC3 pipeline?

I need to get hold of the Attributes on another Controller (i.e. not the current one being executed).

One way to do this is as follows:

    Type controllerType = Type.GetType("App1.UI.Web.Controllers." + controllerName + "Controller", true);
    object[] controllerAttributes = controllerType.GetCustomAttributes(true);

Is there a better, less brittle, way to do the same using the MVC pipeline? I don't want to instantiate the controller, I just want it's attributes.

Upvotes: 1

Views: 376

Answers (1)

Nick Bork
Nick Bork

Reputation: 4841

Before you get rolling too far, keep in mind that a Controller doesn't have to end with the suffix "Controller". The default naming convention for MVC controllers is to append the word "Controller" on to the class. So your defaults are "HomeController" and "AboutController". You could easily create a class called "MyHome" or "Dashboard" and have it inherit from Controller and it would be a controller without having the "Controller" suffix.

I had created a route constraint in the past. Here is a snippet of code I used:

 List<Type> _type = Assembly
                            .GetCallingAssembly()
                            .GetTypes()
                            .Where(type => type.IsSubclassOf(typeof(Controller)))
                            .ToList()

What the code does is looks in the current assembly for all classes that are a controller. You could also add in some code in to the where like :

 .Where(type => type.IsSubclassOf(typeof(Controller)) && type.Name.ToLower() == "homecontroller")

Upvotes: 2

Related Questions