Ali Hussain
Ali Hussain

Reputation: 896

want to call controller method from class and get controller context without making request to controller?

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.

Upvotes: 3

Views: 3739

Answers (1)

Shaiju T
Shaiju T

Reputation: 6607

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

Upvotes: 4

Related Questions