簡體   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