ASP.NET MVC 5 - (HTTP Error 404.0 - Not Found) with long non-existing URL

a 夏天 提交于 2019-11-28 06:05:45

Solved. To point all non-existing urls to your error page, do the following:

  • Add the code below at the end of your RouteConfig.cs file:

    public static void RegisterRoutes(RouteCollection routes)
    {
        // Default
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    
        // Add this code to handle non-existing urls
        routes.MapRoute(
            name: "404-PageNotFound",
            // This will handle any non-existing urls
            url: "{*url}",
            // "Shared" is the name of your error controller, and "Error" is the action/page
            // that handles all your custom errors
            defaults: new { controller = "Shared", action = "Error" }
        );
    }
    
  • Add the code below to your Web.config file:

    <configuration>
        <system.webServer>
           <modules runAllManagedModulesForAllRequests="true"></modules>
        </system.webServer>
    
        <system.web>
           <httpRuntime relaxedUrlToFileSystemMapping="true" />
        </system.web>
    </configuration>
    

That should point all the non-existing urls such as (/ad/asd/sa/das,d/asd,asd.asd+dpwd'=12=2e-21) to your error page.

Another approach would be to add this to your web.config inside of the system.web element

<system.web>
<!-- ... -->

<!--Handle application exceptions-->
<customErrors mode="On">

  <!--Avoid YSOD on 404/403 errors like this because [HandleErrors] does not catch them-->
  <error statusCode="404" redirect="Error/Index" />
  <error statusCode="403" redirect="Error/Index" />
</customErrors>

</system.web>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!