What better way to organize and work with ASP.NET MVC routes?

Asked

Viewed 605 times

6

What better way to organize and work with ASP.NET MVC routes?

While we have 1, 2 routes, it’s quiet, but when do we have 500 ? 600 ? In an enterprise application there are many routes, which is the best way to organize them without losing control/performance ?

2 answers

7


Using as many routes as possible Default.

For example:

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

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

Just with these statements, you have the route to all Controllers of its application, having as a standard the Action Index and the Id parameter as optional.

If the goal is to have alternative names for your routes, you can put alternative routes before the route Default or separate alternative routes into another file. If you choose the separation path, don’t forget to call the two route records in your Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RotasAlternativasConfig.RegisterRoutes(RouteTable.Routes); // Crie um arquivo chamado RotasAlternativasConfig no diretório App_Start
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();
    }
}

5

To organize your routes, you should always put the most specific first and then the more generic ones. Because once Asp.net finds a route that satisfies its parameters, it will use it and ignore the next ones.

Once this is done, the best way to ensure that you won’t "get lost" with many routes and that everything will continue to work as you create or modify the routes, is to test them with Unit Test.

I usually use the nuget package Mvcroutetester to do this.

Install-Package MvcRouteTester

Below is the documentation of the same, where you will find examples:

https://mvcrouteunittester.codeplex.com/

  • 1

    +1 for MvcRouteTester. Very good.

  • I recommend using the Glimpse. You can see the routes and values well, as well as other detailed information about what is happening on the server.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.