Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Custom Route ASP.NET MVC5

I haven't used .NET Routing before. I have a URL: http://myurl.com/Account/Login/?IsIPA=true. I want to be able to hit this URL with the following: http://myurl.com/IPA

This is the only custom route I want hit.

Can I create a route just for a single URL like this?

My code that isn't working is:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    routes.MapRoute("IPA", "Account/Login/{IsIPA}", new { controller = "Account", action = "Login", IsIPA = "true" });
}

I get the error:

The constraint entry IsIPA on the route with route template Account/Login/{IsIPA}=True must have a string value or be of a type which implements System.Web.Routing.IRouteConstraint.

like image 750
Rhys Stephens Avatar asked Mar 03 '15 05:03

Rhys Stephens


1 Answers

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.

like image 198
NightOwl888 Avatar answered Nov 07 '22 15:11

NightOwl888