Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save seangwright/d8642cc4aa8c8c5058eb7c18e987a242 to your computer and use it in GitHub Desktop.
Save seangwright/d8642cc4aa8c8c5058eb7c18e987a242 to your computer and use it in GitHub Desktop.
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