AttributeRouting - Method to get routes in assembly

喜你入骨 提交于 2019-12-24 04:42:09

问题


I want to use AttributeRouting with Orchard CMS. To do so I need to implement an IRouteProvider with a method that returns an list of Orchard RouteDescriptors.

I need a way to get the routes list so I can do something like this:

   public IEnumerable<RouteDescriptor> GetRoutes()
    {
        return _routes ?? (_routes = MvcRouting.GetRoutes(GetType().Assembly).Select(route => new RouteDescriptor
        {
            ...
        }).ToArray());
    }

This method is from MvcRouting but I want to use the more feature rich AttributeRouting but cannot find a way to scan current assembly for routing attributes. Need a way for AttributeRouting to return the list of routes that I can project into a list of RouteDescriptors but not actually registering them, leaving that to Orchard.

 public class RouteDescriptor {
    public string Name { get; set; }
    public int Priority { get; set; }
    public System.Web.Routing.RouteBase Route { get; set; }
    public System.Web.SessionState.SessionStateBehavior SessionState { get; set; }
}

If I wanted to register the routes directly (in a non-Orchard project) I would use the following AttributeRouting extension methods:

  routesCollection.MapAttributeRoutes(config =>
        {
            config.AddRoutesFromAssembly(Assembly.GetExecutingAssembly());
        }

But this won't place nice with other Orchard modules. So need to take the approach above.

Any way you can think of?


回答1:


As Bertrand already noted, what you need is a simple reflection over currently available Controller types.

  1. Implement IRouteProvider as you already did.
  2. Grab all Controller types exported by currently enabled modules

    IExtensionManager _extensions;
    ShellBlueprint _shell;
    ...
    var types = _extensions
                    .LoadFeatures(_extensions.EnabledFeatures(_shell.Descriptor))
                        .SelectMany(feature => feature
                            .ExportedTypes
                            .Where(t => typeof(Controller).IsAssignableFrom(t)));
    
  3. Loop over methods of each of the types above and pick those that have a given attribute defined. For each of the methods picked, fetch its name (action name), name of the assembly that contains its declaring type (area name) along with the attribute data (route pattern etc.).

  4. Having the collection above in hand, you can simply loop over it and return new RouteDescriptor{ ... } for each.


来源:https://stackoverflow.com/questions/15515863/attributerouting-method-to-get-routes-in-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!