I'd like to implement a base controller on one of my controllers. Within that base controller, I'd like to be able to get the current executing ActionResult name.
我想在我的一个控制器上实现一个基本控制器。在该基本控制器中,我希望能够获得当前正在执行的ActionResult名称。
How would I go about doing this?
我该怎么做呢?
public class HomeController : ControllerBase
{
public ActionResult Index()
{
And;
public class ControllerBase : Controller
{
public ControllerBase()
{
//method which will get the executing ActionResult
}
}
1 个解决方案
#1
14
You can't know this in the constructor of the controller as the controller is currently being instantiated and no action could be called yet. However you could override the Initialize method and fetch the action name from the routing engine:
您无法在控制器的构造函数中知道这一点,因为控制器当前正在实例化,并且尚未调用任何操作。但是,您可以覆盖Initialize方法并从路由引擎中获取操作名称:
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
var actionName = requestContext.RouteData.Values["action"];
}
#1
14
You can't know this in the constructor of the controller as the controller is currently being instantiated and no action could be called yet. However you could override the Initialize method and fetch the action name from the routing engine:
您无法在控制器的构造函数中知道这一点,因为控制器当前正在实例化,并且尚未调用任何操作。但是,您可以覆盖Initialize方法并从路由引擎中获取操作名称:
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
var actionName = requestContext.RouteData.Values["action"];
}