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

6

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

While we have 1, 2 routes, it's quiet, but when do we get 500? 600? In a corporate application there are many routes, what is the best way to organize them without losing control / performance?

    
asked by anonymous 07.08.2014 / 23:56

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" }
        );
    }
}

Only with these declarations, you have the path to all Controllers of your application, defaulting to%% Index and Id as optional.

If your goal is to have alternate names for your routes, you can put the alternate routes before the Action route or separate the alternate routes into another file. If you choose the separation path, be sure to call the two routing records in your Default :

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();
    }
}
    
08.08.2014 / 03:21
5

To organize your routes, you should always put the most specific ones first and then the more generic ones. For as soon as ASP.NET finds a route that satisfies its parameters, it will use it and ignore the next.

Once this is done, the best way to ensure that you do not 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 MvcRouteTester package to do this.

Install-Package MvcRouteTester

Below is the documentation for it, where you will find examples:

link

    
08.08.2014 / 17:09