Skip to content

Instantly share code, notes, and snippets.

@sebnilsson
Created June 26, 2014 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebnilsson/552978ed30ae1049ff69 to your computer and use it in GitHub Desktop.
Save sebnilsson/552978ed30ae1049ff69 to your computer and use it in GitHub Desktop.
ASP.NET MVC 5: Testable RouteCollection.MapMvcAttributeRoutes
public static void MapMvcAttributeRoutes(
this RouteCollection routeCollection,
Assembly controllerAssembly,
IInlineConstraintResolver constraintResolver = null)
{
var controllerTypes = (from type in controllerAssembly.GetExportedTypes()
where
type != null && type.IsPublic
&& type.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)
&& !type.IsAbstract && typeof(IController).IsAssignableFrom(type)
select type).ToList();
var attributeRoutingAssembly = typeof(RouteCollectionAttributeRoutingExtensions).Assembly;
var attributeRoutingMapperType =
attributeRoutingAssembly.GetType("System.Web.Mvc.Routing.AttributeRoutingMapper");
var mapAttributeRoutesMethod = attributeRoutingMapperType.GetMethod(
"MapAttributeRoutes",
BindingFlags.Public | BindingFlags.Static,
null,
new[] { typeof(RouteCollection), typeof(IEnumerable<Type>), typeof(IInlineConstraintResolver) },
null);
constraintResolver = constraintResolver ?? new DefaultInlineConstraintResolver();
mapAttributeRoutesMethod.Invoke(null, new object[] { routeCollection, controllerTypes, constraintResolver });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment