Editing Routes in ASP.NET MVC
- by imran_ku07
Introduction : Phil Haack's had written two great articles about Editable Routes, Editable Routes or Editable Routes Using App_Code.These Article are great. But if you not need to unit test your Routes and don't care about restart Application Domian during editing your Routes then global.asax file is the fastest and easiest to achieve the same. In this Article I will use Global.asax file instead of Global.asax.cs file for defining Routes and you will also see how this whole process will works.
Description :
You just need to Cut (or Copy) the code inside Global.asax.cs and paste it in Global.asax inside runat server tag.
You can simply do this by cutting the code of Global.asax.cs,
and paste it inside Global.asax,
Easy and quick ,Now you can change Global.asax without compiling the application.
How this works : I think it is worth here to see what is happening here.
Actually, ASP.NET will use Global.asax file to create a class named global_asax within ASP namespace and place all the code in Global.asax inside the class global_asax class which is created at runtime,
namespace ASP { public class global_asax: NerdDinner.MvcApplication { //Any definitions defined in Global.asax like Application_Start method } }
Which inherits from class defined in Application tag,
<%@ Application Codebehind="Global.asax.cs" Inherits="NerdDinner.MvcApplication" Language="C#" %>
Actually ASP.NET creates a pool of application objects of this class, which varies from 1 to 100. Every request take one of these application objects to a serve incoming requests. After receiving an application object then it will call application specific events, like Application_Start(for only firstRequest), Application_BeginRequest(for every request), and so on. Therefore if these methods are defined in global_asax class then ASP.NET will call these method from global_asax, if not then it will use base class methods may be defined in Global.asax.cs(the concept known as shadowing or hiding).
Summary : In this article, I showed how easily and quickly you can make your Routes Editable. But also note that any change in global.asax results in Application Domain restart and this technique also makes your Route Unit Test difficult.