3

I have got a plain ASP.NET MVC 4 Internet application. When I go to /NotFound, I get his error page:

enter image description here

while if I go to /Home/About/something/nonexistent, I get

enter image description here

Can anyone tell me what's happening under the hood?

I've gone in GetControllerInstance of the DefaultControllerFactory class in System.Web.Mvc and I can see:

throw new HttpException(404,
String.Format(
    CultureInfo.CurrentCulture,
    MvcResources.DefaultControllerFactory_NoControllerFound,
    requestContext.HttpContext.Request.Path));

but I can't figure out where that exception is being handled. Am I on the right track there?

DavidS
  • 2,179
  • 4
  • 26
  • 44

1 Answers1

0

The first case is a .NET error page - because your /NotFound URL is covered by your routes, but the controller isn't found. In other words, MVC handles the request because it has routes that match it (e.g. "{controller}/{action}/{id}" where all three parameters are optional or have defaults), but then finds that it's in over its head.

Assuming you're using the default routes, the exception is indeed thrown by GetControllerInstance - because there's no NotFoundController.

Going instead to "/Home/NotFound" would throw a similar exception (also a 404 HttpException) from Controller.HandleUnknownAction, because "NotFound" now is used as the action name.

In your second case, the URL doesn't match any route, so MVC doesn't handle it - instead IIS tries to handle it itself, and shows its own 404 page, because it also doesn't find any other handlers or actual files at the path indicated by the URL.

As for how to handle all those cases, this stackoverflow question should help.

The short version of where the exception thrown from GetControllerInstance is handled is "it isn't - in any place that you have control of". You can either use the global Application_Error method in global.asax, or use one of the many other approaches in the linked question (for example, replacing the controller factory with one that has GetControllerInstance overridden to add exception handling closer to where the problem occurs).

Community
  • 1
  • 1
JimmiTh
  • 7,389
  • 3
  • 34
  • 50