2017-12-18 85 views
0

我正在使用動態加載的程序集作爲MVC控制器(插件/附加框架)的源代碼。我無法找到在引用程序集中映射控制器的屬性路由的方法。引用/外部程序集中的MapMvcAttributeRoutes

我試過從引用的程序集中調用MapMvcAttributeRoutes(就像文章中提到的那樣可以在Web API中工作),但那沒用。

如何映射引用程序集中控制器的屬性路由?

編輯:

我有一個主要的MVC應用程序從文件加載程序集。這些組件的結構,像這樣:

Add-On Assembly Structure

我擴展的代碼創建一個控制器和尋找的看法,但我可以找到關於如何處理這樣的外部組件規定(圖)RouteAttribute沒什麼說明:

[RoutePrefix("test-addon")] 
public class MyTestController : Controller 
{ 
    [Route] 
    public ActionResult Page() 
    { 
     return View(new TestModel { Message = "This is a model test." }); 
    } 
} 
+1

是自定義框架還是任何CMS?最好展示一些代碼以更好地理解它。 –

+0

請用一些代碼更詳細地敘述問題。 – inthevortex

回答

0

我設法找到一個解決方案:手動解析路由屬性到路由字典。也許沒有這樣做100%正確的,但是這似乎工作至今:

public static void MapMvcRouteAttributes(RouteCollection routes) 
{ 
    IRouteHandler routeHandler = new System.Web.Mvc.MvcRouteHandler(); 

    Type[] addOnMvcControllers = 
     AddOnManager.Default.AddOnAssemblies 
      .SelectMany(x => x.GetTypes()) 
      .Where(x => typeof(AddOnWebController).IsAssignableFrom(x) && x.Name.EndsWith("Controller")) 
      .ToArray(); 

    foreach (Type controller in addOnMvcControllers) 
    { 
     string controllerName = controller.Name.Substring(0, controller.Name.Length - 10); 
     System.Web.Mvc.RoutePrefixAttribute routePrefix = controller.GetCustomAttribute<System.Web.Mvc.RoutePrefixAttribute>(); 
     MethodInfo[] actionMethods = controller.GetMethods(); 
     string prefixUrl = routePrefix != null ? routePrefix.Prefix.TrimEnd('/') + "/" : string.Empty; 

     foreach (MethodInfo method in actionMethods) 
     { 
      System.Web.Mvc.RouteAttribute route = method.GetCustomAttribute<System.Web.Mvc.RouteAttribute>(); 

      if (route != null) 
      { 
       routes.Add(
        new Route(
         (prefixUrl + route.Template.TrimStart('/')).TrimEnd('/'), 
         new RouteValueDictionary { { "controller", controllerName }, { "action", method.Name } }, 
         routeHandler)); 
      } 
     } 
    } 
} 

看似過度修剪,實際上只是爲了確保任何條件下都沒有任何多餘的「/」在開始,中間或結束。

相關問題