Branislav Abadjimarinov's technical blog

ASP.NET MVC default route problem

Posted in MVC, ASP.NET, ASP.NET MVC by Branislav Abadjimarinov on 10/26/2009 1:09:00 PM - CST

If you are working with ASP.NET MVC you definitely have seen that in the startup project in Visual Studio in Global.asax file there is a default route added like this:

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

It is very useful to quickly show how the MVC works but in commercial projects I'll suggest  not to use a default route for handling /{Controller}/{Action} requests in ASP.NET MVC. By doing that you can get a ton of these exceptions:

System.Web.HttpException: The controller for path '/MyCustomPath/' could not be found or it does not implement IController.

The reason for this is that when you make a request for non-existing path like /MyCustomPath/ the MVC Controller factory will try to instantiate a class inheriting IController and named "MyCustomPath" and when It doesn't find it an exception will be thrown.
If the non-existing url is in some static file like .css or .js or the html of the page you can get a lot of these exceptions in just a few seconds if the web server is under a heavy load.

The solution is simple - just remove the default route and add explicitly routes with the controllers you actually use. By doing that you'll get a 404 without the exception.

Comments

Trackback  on 11/21/2009 7:07:56 PM - CST
Gravatar
Posted by Pablo on 2/2/2010 9:02:37 AM - CST
Thanks for answering my post on stackoverflow on .NET MVC + CMS.
Basically my CMS requires me to add an HTTP Handler in front of every request: add verb="*" path="*" type="Cms.ASPDelivery.HttpRequestHandlerFactory, CmsDelivery" When you request an item on the server, the handler (controller) will match the item's contents (model) to the template assigned to it (view). The thing is that my template is just a regular aspx page. Basically I am puzzled on how am I going to avoid the HomeController to be on the way of my Http Handler. Could you tell me your setup (or blog about it)? :)
Gravatar
Posted by Raghav on 11/14/2011 12:53:58 PM - CST
Thanks Brainslav. I was searching all over the net for the resolution for my Http 404 and finally found the answer in the above post. Thanks again.
--Raghav
Gravatar
Posted by John Madsen on 2/15/2012 5:27:25 PM - CST
Hello,
Thanks for this amazing blog post. google

Add Comment

Please enter your name. Please enter a valid email. Please enter a valid website.
Please supply a comment.
© Copyright 2017 Powered by AtomSite 1.3.0.0