StructureMap controller factory and null controller instance in MVC

前端 未结 4 1102
不知归路
不知归路 2021-02-08 10:38

I\'m still trying to figure things out with StructureMap and one of the issues i\'m running into is my Controller Factory class blowing up when a null controller type is passed

4条回答
  •  轮回少年
    2021-02-08 11:08

    What I think you need to do is exactly the same thing that the default MVC controller factory does on the GetControllerInstance method. If you look at the Microsoft source code for DefaultControllerFactory at http://aspnetwebstack.codeplex.com/ you will see that the DefaultControllerFactory throws a 404 Exception when controllerType is null. Here is how we do it based on this information:

     public class StructureMapControllerFactory : DefaultControllerFactory
     {
          protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
          {
               if (controllerType == null)
                    return base.GetControllerInstance(requestContext, controllerType);
               var controller = ObjectFactory.GetInstance(controllerType);
               return (IController)controller;
          }
     }
    

    Basically this will ensure that, when user enters an invalid route the application handles it as a 404 error.

提交回复
热议问题