有没有办法通过 ASP.NET MVC3 管道获取控制器类型?

发布于 2024-12-19 17:08:15 字数 324 浏览 2 评论 0原文

我需要获取另一个控制器上的属性(即不是当前正在执行的控制器)。

一种方法如下:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偏爱你一生 2024-12-26 17:08:15

在你深入之前,请记住控制器不必以后缀“Controller”结尾。 MVC 控制器的默认命名约定是将“Controller”一词附加到类上。所以你的默认值是“HomeController”和“AboutController”。您可以轻松创建一个名为“MyHome”或“Dashboard”的类,并让它继承自 Controller,它将是一个没有“Controller”后缀的控制器。

我过去创建了一个路线约束。以下是我使用的代码片段:

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

该代码的作用是在当前程序集中查找作为控制器的所有类。您还可以在其中添加一些代码,例如:

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

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")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文