Created
January 10, 2017 21:09
-
-
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
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
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