Asp.net mvc 3- get the current controller instance (not just name)

前端 未结 2 500
日久生厌
日久生厌 2020-12-09 04:10

I know how to get the current controller name

HttpContext.Current.Request.RequestContext.RouteData.Values[\"controller\"].ToString();

But i

2条回答
  •  一整个雨季
    2020-12-09 04:45

    By default you can only access the current Controller inside a controller with ControllerContext.Controller or inside a view with ViewContext.Context. To access it from some class you need to implement a custom ControllerFactory which stores the controller instance somewhere and retrieve it from there. E.g in the Request.Items:

    public class MyControllerFactory : DefaultControllerFactory
    {
        public override IController CreateController(RequestContext requestContext, string controllerName)
        {
            var controller = base.CreateController(requestContext, controllerName);
            HttpContext.Current.Items["controllerInstance"] = controller;
            return controller;
        }
    }
    

    Then you register it in your Application_Start:

    ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
    

    And you can get the controller instance later:

    public class SomeClass
    {
        public SomeClass()
        {
            var controller = (IController)HttpContext.Current.Items["controllerInstance"];
        }
    }
    

    But I would find some another way to pass the controller instance to my class instead of this "hacky" workaround.

提交回复
热议问题