ASP.NET MVC - Catch All Route And Default Route

后端 未结 8 1968
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 04:15

In trying to get my application to produce 404 errors correctly, I have implemented a catch all route at the end of my route table, as shown below:

 routes.M         


        
8条回答
  •  鱼传尺愫
    2020-11-28 05:04

    My Solution is 2 steps.

    I originally solved this problem by adding this function to my Global.asax.cs file:

    protected void Application_Error(Object sender, EventArgs e)
    

    Where I tried casting Server.GetLastError() to a HttpException, and then checked GetHttpCode. This solution is detailed here:

    ASP.NET MVC Custom Error Handling Application_Error Global.asax?

    This isn't the original source where I got the code. However, this only catches 404 errors which have already been routed. In my case, that ment any 2 level URL.

    for instance, these URLs would display the 404 page:

    www.site.com/blah

    www.site.com/blah/blah

    however, www.site.com/blah/blah/blah would simply say page could not be found. Adding your catch all route AFTER all of my other routes solved this:

    routes.MapRoute(
                "NotFound",
                "{*url}",
                new { controller = "Errors", action = "Http404" }
            );
    

    However, the NotFound route does not seem to route requests which have file extensions. This does work when they are captured by different routes.

提交回复
热议问题