Given an HttpContext (or HttpContextBase), is there a way to get an instance of the Controller?
An HttpContext object will encapsulate specific details of a single HTTP request. Properties of this class include the Request object, the Response object, the Session object, and an AllErrors property which keeps an array of Exception objects accrued during the current request.
The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.
HttpContext access from a background threadHttpContext isn't thread-safe. Reading or writing properties of the HttpContext outside of processing a request can result in a NullReferenceException.
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();
The HttpContext
will hold a reference to the MvcHandler
, which will hold a reference to the RouteData
, which will hold a reference to what controller is being invoked by a particular route.
NB: This doesn't give you the actual controller, only the controller that the specific route is going to catch.
GetController(HttpContextBase httpContext) { var routeData = ((MvcHandler)httpContext.Handler).RequestContext.RouteData; var routeValues = routeData.Values; var matchedRouteBase = routeData.Route; var matchedRoute = matchedRouteBase as Route; if (matchedRoute != null) { Route = matchedRoute.Url ?? string.Empty; } AssignRouteValues(httpContext, routeValues); } protected virtual VirtualPathData getVirtualPathData(HttpContextBase httpContext, RouteValueDictionary routeValues) { return RouteTable.Routes.GetVirtualPath(((MvcHandler)httpContext.Handler).RequestContext, routeValues); } private void AssignRouteValues(HttpContextBase httpContext, RouteValueDictionary routeValues) { var virtualPathData = getVirtualPathData(httpContext, routeValues); if (virtualPathData != null) { var vpdRoute = virtualPathData.Route as Route; if (vpdRoute != null) { RouteDefaults = vpdRoute.Defaults; RouteConstraints = vpdRoute.Constraints; RouteDataTokens = virtualPathData.DataTokens; RouteValues = routeValues; } } }
This code may look familiar, it's because I've adapted it from Phil Haack's route debugger source code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With