2017-12-18 149 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)); 
      } 
     } 
    } 
} 

看似过度修剪,实际上只是为了确保任何条件下都没有任何多余的“/”在开始,中间或结束。