Might be useful. I needed the action in the constructor of the controller, and it appears at this point of the MVC lifecycle, this
hasn't initialized, and ControllerContext = null
. Instead of delving into the MVC lifecycle and finding the appropriate function name to override, I just found the action in the RequestContext.RouteData
.
But in order to do so, as with any HttpContext
related uses in the constructor, you have to specify the full namespace, because this.HttpContext
also hasn't been initialized. Luckily, it appears System.Web.HttpContext.Current
is static.
// controller constructor
public MyController() {
// grab action from RequestContext
string action = System.Web.HttpContext.Current.Request.RequestContext.RouteData.GetRequiredString("action");
// grab session (another example of using System.Web.HttpContext static reference)
string sessionTest = System.Web.HttpContext.Current.Session["test"] as string
}
NOTE: likely not the most supported way to access all properties in HttpContext, but for RequestContext and Session it appears to work fine in my application.