I'm having a heck of a time figuring out how to properly implement my 404 redirecting.
If I use the following
<HandleError()> _
Public Class BaseController : Inherits System.Web.Mvc.Controller
''# do stuff
End Class
Then any unhandled error on the page will load up the "Error" view which works great. http://example.com/user/999 (where 999 is an invalid User ID) will throw an error while maintaining the original URL (this is what I want)
However. If someone enters http://example.com/asdfjkl into the url (where asdfjkl is an invalid controller), then IIS is throwing the generic 404 page. (this is not what I want). What I need is for the same thing above to apply. The original URL stays, and the "NotFound" controller is loaded.
I'm registering my routes like this
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.RouteExistingFiles = False
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.IgnoreRoute("Assets/{*pathInfo}")
routes.IgnoreRoute("{*robotstxt}", New With {.robotstxt = "(.*/)?robots.txt(/.*)?"})
routes.AddCombresRoute("Combres")
routes.MapRoute("Start", "", New With {.controller = "Events", .action = "Index"})
''# MapRoute allows for a dynamic UserDetails ID
routes.MapRouteLowercase("UserProfile", "Users/{id}/{slug}", _
New With {.controller = "Users", .action = "Details", .slug = UrlParameter.Optional}, _
New With {.id = "\d+"} _
)
''# Default Catch All MapRoute
routes.MapRouteLowercase("Default", "{controller}/{action}/{id}/{slug}", _
New With {.controller = "Events", .action = "Index", .id = UrlParameter.Optional, .slug = UrlParameter.Optional}, _
New With {.controller = New ControllerExistsConstraint})
''# Catch everything else cuz they're 404 errors
routes.MapRoute("CatchAll", "{*catchall}", _
New With {.Controller = "Error", .Action = "NotFound"})
End Sub
Notice the ControllerExistsConstraint
? What I need to do is use Reflection to discover whether or not a the controller exists.
Can anybody help me fill in the blanks?
Public Class ControllerExistsConstraint : Implements IRouteConstraint
Public Sub New()
End Sub
Public Function Match(ByVal httpContext As System.Web.HttpContextBase, ByVal route As System.Web.Routing.Route, ByVal parameterName As String, ByVal values As System.Web.Routing.RouteValueDictionary, ByVal routeDirection As System.Web.Routing.RouteDirection) As Boolean Implements System.Web.Routing.IRouteConstraint.Match
''# Bah, I can't figure out how to find if the controller exists
End Class
I'd also like to know the performance implications of this... how performance heavy is Reflection? If it's too much, is there a better way?