Created
May 18, 2019 19:11
-
-
Save seangwright/d8642cc4aa8c8c5058eb7c18e987a242 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class RouteCollectionExtensions | |
{ | |
public static void MapRoute<T>( | |
this RouteCollection routes, | |
string name, | |
string url, | |
Func<T, string> nameOfDefaultAction) where T : Controller | |
{ | |
string controller = typeof(T).RemoveControllerSuffix(); | |
string action = nameOfDefaultAction(default); | |
routes.MapRoute(name, url, new | |
{ | |
controller, | |
action | |
}); | |
} | |
/** | |
* "Controller".Length | |
*/ | |
private const int CONTROLLER_SUFFIX_LENGTH = 10; | |
public static string RemoveControllerSuffix(this Type controllerType) | |
{ | |
Guard.Against.Null(controllerType, nameof(controllerType)); | |
if (!typeof(Controller).IsAssignableFrom(controllerType)) | |
{ | |
throw new ArgumentException($"Type [{controllerType.Name}] is not assignable from [{nameof(Controller)}]"); | |
} | |
return controllerType | |
.Name | |
.Substring(0, controllerType.Name.Length - CONTROLLER_SUFFIX_LENGTH); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment