How to handle an exception in an ASP.NET MVC factory controller

I have an ASP.NET MVC 2 application with a custom StructureMap factory controller to handle dependency injection for my controllers:

public class StructureMapControllerFactory : DefaultControllerFactory { public override IController CreateController(RequestContext context, string controllerName) { Type controllerType = base.GetControllerType(context, controllerName); return ObjectFactory.GetInstance(controllerType) as IController; } } 

I would like to know how I can handle exceptions in this factory controller so that they can be redirected to ~ / Views / Shared / Error.aspx just as they are in the controller with HandleError attribute. Currently, this does not make exceptions, even though the CustomErrors attribute is set to "On".

I can currently throw such an exception using a URL like ~ ~ / DoNotExist / edit / 1. Default route:

 routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); 

MVC maps this route and passes the controller name "DoNotExist" to my factory controller. GetControllerType then returns null and throws a link reference exception in a call to StructureMap. Then I would like to be able to deal with this exception.

Please note that adding a subsequent catch route will not completely solve this problem - MVC corresponds to the default route.

I know that I can solve this problem by setting default route restrictions for the controller, but the question is more general about how I can use regular MVC ~ / Views / Shared / Error.aspx in the factory.

Note that I do not want the answer to require a tight connection between the factory controller and a specific MVC application. Ideally, this factory should not be in the same solution in the referenced assembly.

+6
exception-handling asp.net-mvc factory
source share
2 answers

Perhaps you can adapt this factory controller to handle exceptions.

+2
source share

I would create an error controller that is called by the factory controller if it cannot find the requested controller. Then, in this case, override HandleUnknownAction to capture any action that is requested.

 public class StructureMapControllerFactory : DefaultControllerFactory { public override IController CreateController(RequestContext context, string controllerName) { Type controllerType = base.GetControllerType(context, controllerName); if (controllerType == null) return ObjectFactory.GetInstance(ErrorController) as IController; else return ObjectFactory.GetInstance(controllerType) as IController; } } 
0
source share

All Articles