I'm trying to execute a controller's Action Method programatically and I'm not sure how.
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 determine the controller/method .. because that route might not have been wired up.
Eg.
// 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(); // <-- HERE!
}
return result;
}
}
.. and that method is ..
public static void Execute404NotFound(this Controller controller)
{
result = new 404NotFound();
// Setup any ViewData.Model stuff.
result.ExecuteResult(controller.ControllerContext); // <-- RUNTIME
// ERROR's HERE
}
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 'Execute404NotFound
' on this controller instance. That's fine .. until it runs the ExecuteResult(..)
method. Why? the controller has no ControllerContext
data. As such, the ExecuteResult
crashes because it requires some ControllerContext
.
So - can someone out there help me? see what I'm doing wrong.
Remember -> i'm trying to get my controller factory to manually / programmatically call a method on a controller which of course would return an ActionResult.
Please help!
UPDATE:
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.