Given an HttpContext (or HttpContextBase), is there a way to get an instance of the Controller?
original title: "asp.net mvc - Can I get the controller from the HttpContext?"
Given an HttpContext (or HttpContextBase), is there a way to get an instance of the Controller?
Annetaanko HttpContext (tai HttpContextBase), onko tapa saada ohjaimen ilmentymä?
Tämä on yhteenveto käännöksen jälkeen. Jos haluat tarkastella koko käännöstä, napsauta käännä-kuvaketta
The
HttpContext
will hold a reference to theMvcHandler
, which will hold a reference to theRouteData
, which will hold a reference to what controller is being invoked by a particular route.This code may look familiar, it's because I've adapted it from Phil Haack's route debugger source code.
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.
Not easily, you will basically have to first get the MvcHandler from the RouteData, then build the Controller. Even then, it won't give you the instance used to handle the action as it will be a new instance of the controller.