Farhan Ullah
Farhan Ullah

Reputation: 13

Some basic questions about Routing in ASP.NET MVC

I'm trying to learn ASP.NET MVC and have a few questions about routing.

Print is a controller, with a Show action, that takes a parameter and returns it back as string.

Consider the code

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

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

        routes.MapRoute(
          name: "Print",
          url: "Print/{action}/{id}",
           defaults:  new { controller = "Print", action = "Show", id = UrlParameter.Optional });


    }

Why do I get a 404 error when I try host:xxxxx/Print/xxx...? Shouldn't it take me to the Show action?

Also if I set url:Print, and try host:xxxxx/Print I get the same error. It should take me to the Show action.

Similarly if I set url:Print/{action}/{id} and try host:xxxxx/Print/Show it gives the same error, even though the parameter is optional, and should return blank?

But if I interchange the two routes such that the Print route is first in precedence and Home/Index in second, I do not get any errors in any cases? host:xxxxx/Print shows blank, host:xxxxx/Print/Show shows blank and host:xxxxx/Print/Show/xxx... returns some value.

Why do I get errors if I set it as the second route?

Upvotes: 1

Views: 67

Answers (1)

Victor
Victor

Reputation: 8925

Change the routes register order to:

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

    routes.MapRoute(
        name: "Print",
        url: "Print/{action}/{id}",
        defaults: new { controller = "Print", action = "Show", id = UrlParameter.Optional });

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

The routes in the RegisterRoutes() are analyzed in order they are added to the routes. The Default route pattern is universal, therefore the second doesn't work. The MVC trying to find the Show action in the Home controller and does not finding it. Therefore it report the 404 error.

If look at the RouteCollection declaration it is inherited from IList<T>. So, the routes analyzed in order they added to the routes table.

Any your routes should be added before the Default route.

Upvotes: 1

Related Questions