Ignoring Favicon.ico in ASP.Net MVC

I was hacking around on a custom controller factory in ASP.Net MVC which leveraged Ninject and StructureMap under Azure. After working around a couple security issues, I kept running into a weird exception where the type passed into my ControllerFactory was null.

Here was my original code:

   1: public class ControllerFactory2 : DefaultControllerFactory
   2: {
   3:     protected override IController GetControllerInstance(Type controllerType)
   4:     {
   5:         return (IController) NinejctManager.GetIntance(controllerType);
   6:     }
   7: }

 

As you can see, my first problem was I was not checking for null in the controllerType paramater. Looking at the MVC source, when this is null the DefaultControllerFactory in ASP.Net MVC will throw a 404 exception; so the “fix” is to add a check for null and then pass it to the base class.

   1: public class ControllerFactory2 : DefaultControllerFactory
   2: {
   3:     protected override IController GetControllerInstance(Type controllerType)
   4:     {
   5:         if (controllerType == null)
   6:             return base.GetControllerInstance(controllerType);
   7:  
   8:         return (IController) NinejctManager.GetIntance(controllerType);
   9:     }
  10: }

 

While this would work, there was still something getting through which appeared to be throwing an exception on every other request or two. WIth a little more debugging, I found that the RawUrl on the Request object had the following value: “/favicon.ico”.  As annoying as this is, it is easily fixable by the following to my Routes: routes.IgnoreRoute("favicon.ico");.