ASP.NET MVC - Catch All Route And Default Route

后端 未结 8 1828
伪装坚强ぢ
伪装坚强ぢ 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.

    0 讨论(0)
  • 2020-11-28 05:09

    Use route constraints

    In your case you should define your default route {controller}/{action}/{id} and put a constraint on it. Probably related to controller names or maybe even actions. Then put the catch all one after it and it should work just fine.

    So when someone would request a resource that fails a constraint the catch-all route would match the request.

    So. Define your default route with route constraints first and then the catch all route after it:

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        new { controller = "Home|Settings|General|..." } // this is basically a regular expression
    );
    routes.MapRoute(
        "NotFound",
        "{*url}",
        new { controller = "Error", action = "PageNotFound" }
    );
    
    0 讨论(0)
提交回复
热议问题