Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Why is RouteData Null in my Asp.Net Mvc Controller?

Posted on: 2014-08-13

This article explains how to not having the RouteData null in the controller.

If you have your own implementation of Controller and that you use base.RouteData you may have some special surprise. Sometime it can be null.

 public class BaseController : Controller { public BaseController() { var routeData = base.RouteData;// This can be wrong } } 

The problem is that the routing may have not been yet analyzed by the controller. This is why you must not use the RouteData in the controller. The place to be sure that this one is set is in OnActionExecuting. MSDN explains that the RouteData is not defined before being called by Initialize. This Initialize method is private and is called by Asp.Net

 public class BaseController : Controller { public BaseController() { } protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); var routeData = base.RouteData; } } 

After calling the base.OnActionExecution(...) you can call the RouteData.