Skip to content

Instantly share code, notes, and snippets.

@tiesont
Created January 10, 2017 21:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiesont/186b0cc134f88853a77ba4b1e475143a to your computer and use it in GitHub Desktop.
Save tiesont/186b0cc134f88853a77ba4b1e475143a to your computer and use it in GitHub Desktop.
Demonstrates how to remove "home" from routing without needing to explicitly map other controllers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MyNamespace
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("content/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
routes.LowercaseUrls = true;
routes.MapRoute(
name: "DefaultSansHome",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { controller = new RootRouteConstraint<Controllers.HomeController>() }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
}
public class RootRouteConstraint<T> : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name);
return values["action"] == null ? false : rootMethodNames.Any(m => m.Equals(values["action"].ToString(), System.StringComparison.OrdinalIgnoreCase));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment