繁体   English   中英

使用Application.Controller MVC

[英]Using Application.Controller MVC

好的,基本上我正在构建一个nuget包,我希望该类要做的一件事是获取当前的应用程序控制器

因此,目前在主项目中,我执行以下操作

using SolutionName.Website.MVC5.Controllers;

我想要做的是

using this.Application.Controllers;

因此,它会动态地为安装软件包的任何解决方案填充名称空间。

我在这里坐了一个小时,仔细研究了可能的排列,还用谷歌搜索了一下,但不确定到底要用什么搜索

这包括API控制器,我正在使用MVC 5

干杯

马丁

下面的几点思考将为您提供所有以“ Controller”结尾的文件的命名空间。

var namespaces = this.GetType().Assembly.GetTypes()
    .Where(t => t.Name.EndsWith("Controller"))
    .Select(x => x.Namespace).Distinct().ToList();

您需要从代码中调用此Global.asax ,最好在Global.asax调用它。

请记住,您的控制器可能分散在多个名称空间中,因此必须考虑其他逻辑。 命名空间的数量仅取决于您对应用程序的构造程度。

另外,您也可以提取直接从“ System.Web.Mvc.Controller”继承的类型,如Andrew Whitaker所指出的。

var namespaces = this.GetType().Assembly.GetTypes()
    .Where(t => t => t.IsSubclassOf(typeof(Controller)))
    .Select(x => x.Namespace).Distinct().ToList();

在使用@DavidL和@AndrewWhitaker给我的信息之后,我想我会发布一些有关如何在MVC应用程序中工作的代码片段,因为与问题并存可能很有用

我在下面创建了课程

public class GetControllerNameSpace
{
    public static string NamespaceTag; 
    public void GetControllerNameSpaceMethod()
    {
        var NamespaceTagList = this.GetType().Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Controller))).Select(x => x.Namespace).Distinct().ToList();
        NamespaceTag = NamespaceTagList.FirstOrDefault();
    }
}

然后在RouteConfig.cs中

using Controllers = GetControllerNameSpace;

然后,这可以让我将信息传递给我的方法

    private static IEnumerable<Type> GetTypesWithFixedControllerRouteAttribute(RouteCollection routes)
            {
                                                         //This is where i am passing the variables
                foreach (Type type in Assembly.GetAssembly(typeof(Controllers.HomeController)).GetTypes())
                {
                    // Register any fixed actions
                    RegisterFixedActionRoutes(type, routes);

                    if (type.GetCustomAttributes(typeof(FixedControllerRouteAttribute), true).Any())
                    {
                        yield return type;
                    }
                }
            }

请注意,这在我的用例中有效,使用@DavidL的帖子中提到的多个控制器名称空间时,可能需要更多工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM