有没有办法通过 ASP.NET MVC3 管道获取控制器类型?
我需要获取另一个控制器上的属性(即不是当前正在执行的控制器)。
一种方法如下:
Type controllerType = Type.GetType("App1.UI.Web.Controllers." + controllerName + "Controller", true);
object[] controllerAttributes = controllerType.GetCustomAttributes(true);
是否有更好、更不易损坏的方法来使用 MVC 管道执行相同的操作?我不想实例化控制器,我只想要它的属性。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在你深入之前,请记住控制器不必以后缀“Controller”结尾。 MVC 控制器的默认命名约定是将“Controller”一词附加到类上。所以你的默认值是“HomeController”和“AboutController”。您可以轻松创建一个名为“MyHome”或“Dashboard”的类,并让它继承自 Controller,它将是一个没有“Controller”后缀的控制器。
我过去创建了一个路线约束。以下是我使用的代码片段:
该代码的作用是在当前程序集中查找作为控制器的所有类。您还可以在其中添加一些代码,例如:
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:
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 :