问题
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 RouteDescriptor
s.
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 RouteDescriptor
s 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.
- Implement
IRouteProvider
as you already did. Grab all
Controller
types exported by currently enabled modulesIExtensionManager _extensions; ShellBlueprint _shell; ... var types = _extensions .LoadFeatures(_extensions.EnabledFeatures(_shell.Descriptor)) .SelectMany(feature => feature .ExportedTypes .Where(t => typeof(Controller).IsAssignableFrom(t)));
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.).
- 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