Map Custom Route ASP.NET MVC5
Route matching is similar to a switch case statement. The url
parameter and any default values and constraints are all considered to determine whether or not it is a match with the incoming URL. If the route matches, it will then create a dictionary of route values based on the configuration. If the route does not match, the next route in the collection is tried until a match is found (or not).
This means the order that routes are specified is important. The default route matches any URL with 0, 1, 2, or 3 segments. Therefore, in most cases you will need to define your custom route before the default route.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "IPA",
url: "IPA",
defaults: new { controller = "Account", action = "Login", IsIPA = "true" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
The above configuration will route http://myurl.com/IPA
to the Controller named Account
and Action method named Login
, and pass the additional route key IsIPA
. This same URL will be built for the Controller/Action/IsIPA combination because it is the first one that matches in the list.
Note that the original URL http://myurl.com/Account/Login/?IsIPA=true
will still work and still route to the same location. This configuration just adds an extra route to that resource.