Moving routes out of Global.asax

Having all of your routes defined in Global.asax is initially quite convenient. However, after a while you might find that your application has grown so large that the long list of route definitions might need to be moved out of Global.asax. Technically, this is a good habit to get into when you first create your application. But many argue that having your routes in an editable file is convenient. However, I would suggest to you that if your routes are changing, odds are that something else has probably caused this change and that the change is probably larger than just a simple routing change!

How to do it...

  1. Start by creating a new MVC application.
  2. Then create a new class in the Models folder called RouteLibrary.cs.
  3. Then copy out the entire RegisterRoutes method in Global.asax and paste it into your new RouteLibrary class.

    Models/RouteLibrary.cs:

    public class RouteLibrary
    {
    public static void RegisterRoutes(RouteCollection routes)
    {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute("Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults);
    }
    }
    
  4. Then in the Global.asax file, make a call to the new RegisterRoutes method.

    Global.asax:

    protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();
    RouteLibrary.RegisterRoutes(RouteTable.Routes);
    }
    
  5. Now you are ready to run your application.

How it works...

You will probably notice that not much has changed here. However, with the route definitions moved into the RouteLibrary you are now able to manage them a bit better. You could even go so far as to create separate methods for each major area of your application, with each method containing all the appropriate routes for that area. In the end, you have more flexibility with routes in the RouteLibrary and you have reduced the number of concerns that your Global.asax file is responsible for.

There's more...

Because there are several people who would suggest that moving your routing into a class of its own removes the convenience of having the route definitions in Global.asax, I will leave you with this bit of advice—consider putting your routing into its own class library. This way, if your routes really do change that often, you can deploy your routing library separate from the rest of your code. Though I don't think your routes will change that often in such a manner, than only the route that needs to be redeployed!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset