Editable Routes Using App_Code

asp.net, asp.net mvc, code comments edit

UPDATE: THIS POST IS DEPRECATED!!! I’ve updated the original post for editable routes to work in medium trust and not require a full app domain reload like this approach does. I think that approach may supersede this approach until I learn otherwise. :)

Yesterday I wrote about a technique using dynamic compilation to allow editing routes after you’ve deployed an application without having to manually recompile your application.

I made use of a FileSystemWatcher to monitor a Config directory and dynamically recompiled code when the code file changed. This has one advantage over using the App_Code directory in that the whole App Domain doesn’t need to get recycled when you make changes to your routes.

Today, my co-worker David Ebbo (who’s a master at ASP.NET Build and Compilation system) pointed out one gaping flaw with my approach. It doesn’t work in Medium Trust because the FileSystemWatcher class demands full trust. Doh!

For many business systems, that may not be a concern. But for my blog engine, it’s a huge concern. There are workarounds to the FileSystemWatcher issues, but I decided to take the easy way out and use the App_Code directory approach, since it handles all that crufty logic for watching the file system for me.

In this case, I simply added a new folder named App_Code to my project and copied Routes.cs to that folder.


I then added a new method to RouteRegistrationExtensions. (Note that the actual code has some null reference checking which I omitted here.)

public static void RegisterAppCodeRoutes(this RouteCollection routes) {
  var type = BuildManager.GetType("Routes", false/*throwOnError*/);
  var registrar = Activator.CreateInstance(type) as IRouteRegistrar;

So instead of the method I wrote in my previous post, I call this method. The nice thing here is that this method doesn’t have to worry about attaching a FileSystemWatcher or handling events and reloading routes.

Any time the Routes.cs file is changed, the entire App Domain is restarted and Application_Start is called again.

I want to also point out that a long while ago, I showed a different approach for editable routes using IronRuby that you might be interested in.

You can download the sample project here which includes both methods for doing editable routes.