Am I in an MVC or Webforms environment?

I’m currently working on an interesting project which is a combination of legacy code built using webforms, as well as a whole bunch of new functionality developed using MVC.  Due to the sheer volume of code and functionality within the existing system there is simply no possibility of rewriting all the existing forms and underlying code to use the MVC, however we are using MVC wherever possible to build new functionality and extend the system.

This leads to some interesting challenges, in particular within shared areas of code that need to work differently when the user is within a webforms part of the solution, compared to when the user is in a MVC based page.

It was therefore necessary to try and figure out if a particular web request cycle is part of MVC or not.  Rather than write some complex set of routines (and I tried to develop a few) I came up with a remarkably simple mechanism – ‘ask’ the MVC routing engine whether it is able to route the current web request.  If it can route the request to an MVC controller then MVC is being used, otherwise we can assume that its a webforms request.

// To determine if its an MVC Request, look at for a 'controller' value in the route data for this request
public bool IsMvcRequest(HttpContext context)
RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
if (routeData != null && routeData.Values["Controller"] != null)
return true;
return false;

The reason that this works within the webforms environment, is that the Routes class is created as public within the global.asax which is executed for all requests, not just mvc.