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!
Models
folder called RouteLibrary.cs
. 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); } }
Global.asax
file, make a call to the new RegisterRoutes
method.Global.asax:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteLibrary.RegisterRoutes(RouteTable.Routes); }
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.
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!