Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I handle an exception in an ASP.NET MVC controller factory
    primarykey
    data
    text
    <p>I have an ASP.NET MVC 2 application with a custom StructureMap controller factory to handle dependency injection for my controllers:</p> <pre><code>public class StructureMapControllerFactory : DefaultControllerFactory { public override IController CreateController(RequestContext context, string controllerName) { Type controllerType = base.GetControllerType(context, controllerName); return ObjectFactory.GetInstance(controllerType) as IController; } } </code></pre> <p>I would like to know how I can handle exceptions in this controller factory so that they can be redirected to the ~/Views/Shared/Error.aspx in the same way as they are in a controller that has the HandleError attribute. Currently exceptions don't do this despite having the CustomErrors attribute set to "On".</p> <p>At the moment I can generate such an exception using a URL like "~/DoesNotExist/edit/1". With the default route:</p> <pre><code>routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); </code></pre> <p>MVC matches this route and passes controller name "DoesNotExist" to my controller factory. The GetControllerType then returns null and causes a null reference exception in the call to StructureMap. I would then like to be able to handle this exception.</p> <p>Note that adding a subsequent catch all route will not resolve this problem - MVC matches the default route.</p> <p>I know I could solve this particular problem by putting constraints on the default route for controller but the question is more general about how I can use the normal MVC ~/Views/Shared/Error.aspx in the factory.</p> <p>Note that I don't want the answer to require tight coupling of the controller factory to the particular MVC application. Ideally this factory should be in a referenced assembly not in the same solution.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload