Home » ASP » ASP.MVC » Why is RouteData Null in my Asp.Net Mvc Controller?

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

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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

One Response so far.

  1. Reboot says:

    ‘MSDN explains that the RouteData is not defined before being called by Initialize’ – where is the explication in given link ?

Leave a Reply to Reboot Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.