title: How can i Execute a Controller's ActionMethod programatically?
body: <p>I'm trying to execute a controller's Action Method programatically and I'm not sure how.</p>
  <p>Scenario:
  When my ControllerFactory fails to find the controller, I wish it to manually execute a single action method which i have on a simple, custom controller. I don't want to rely on using any route data to <em>determine</em> the controller/method .. because that route might not have been wired up.</p>
  <p>Eg.</p>
  <pre><code>// NOTE: Error handling removed from this example.
  public class MyControllerFactory : DefaultControllerFactory
  {
      protected override IController GetControllerInstance(Type controllerType)
      {
          IController result = null;
     
          // Try and load the controller, based on the controllerType argument.
          // ... snip
          // Did we retrieve a controller?
          if (controller == null)
          {
              result = new MyCustomController();
              ((MyCustomController)result).Execute404NotFound(); // &lt;-- HERE!
          }
  
          return result;
      }
  }
  </code></pre>
  <p>.. and that method is ..</p>
  <pre><code>public static void Execute404NotFound(this Controller controller)
  {
      result = new 404NotFound();
      // Setup any ViewData.Model stuff.
      result.ExecuteResult(controller.ControllerContext); // &lt;-- RUNTIME 
                                                          //  ERROR's HERE
  }
  </code></pre>
  <p>Now, when I run the controller factory fails to find a controller, i then manually create my own basic controller. I then call the extension method '<code>Execute404NotFound</code>' on this controller instance. That's fine .. until it runs the <code>ExecuteResult(..)</code> method. Why? the controller has no <code>ControllerContext</code> data. As such, the <code>ExecuteResult</code> crashes because it requires some <code>ControllerContext</code>.</p>
  <p>So - can someone out there help me? see what I'm doing wrong.</p>
  <p>Remember -&gt; i'm trying to get my controller factory to manually / programmatically call a method on a controller which of course would return an ActionResult.</p>
  <p>Please help!</p>
  <h3>UPDATE:</h3>
  <p>I'm also trying to avoid the more common solutions of using a catchall or throwing an exception which is handled in the Application_Exception section. I don't believe they should be proper way to handle this issue .. considering we know what the problem is and as such we should be handling it, there and then.</p>