3

I want to call a controller method from a class and get the controller context without making requests to the controller. What are possible ways of doing that?

I can call method by creating an object of a controller class but I am unable to get controller's context.

var controllerObj = new HomeController()
controllerObj.methodA();

and in methodA request context is not available.

Pac0
  • 21,465
  • 8
  • 65
  • 74
Ali Hussain
  • 765
  • 8
  • 27

1 Answers1

4

Get the instance of a Controller in a class using DependencyResolver.

public class Example
{    
    public static void CallActionMethod()
    {
        var controller = DependencyResolver.Current.GetService<AboutController>();
        controller.ControllerContext = new ControllerContext(System.Web.HttpContext.Current
        .Request.RequestContext, controller);    
        controller.Index();    
    }  
}

Reference

Felix D.
  • 4,811
  • 8
  • 38
  • 72
Shaiju T
  • 6,201
  • 20
  • 104
  • 196