Can I get the controller from the HttpContext?

hackerhasid picture hackerhasid · Mar 14, 2011 · Viewed 37.3k times · Source

Given an HttpContext (or HttpContextBase), is there a way to get an instance of the Controller?

Answer

Bill picture Bill · Jan 26, 2012

For those looking just to get the controller name and not an actual instance, as is needed for custom authorization overrides of AuthorizeCore(httpContext), this is the clean code.

var request = httpContext.Request;
var currentUser = httpContext.User.Identity.Name;
string controller = request.RequestContext.RouteData.Values["controller"].ToString();
string action = request.RequestContext.RouteData.Values["action"].ToString();