【问题标题】:How to handle HTTP 404 with ASP.NET MVC projects如何使用 ASP.NET MVC 项目处理 HTTP 404
【发布时间】:2021-02-20 16:35:48
【问题描述】:

我一直在寻找可以处理 404 错误以将其重定向到设计并命名为 404 错误的页面的方法。

有些文章说我应该在 Route 配置中做一些更改。我更改了它,现在下面的代码是我的 route.config 但仍然无法正常工作

public static void RegisterRoutes(RouteCollection routes)
{
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
               name: "Default2",
               url: "{controller}/{action}/{id}",
               defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
           );

        //404 ERRORS:
        routes.MapRoute(
            name:"404-PageNotFound",
            url: "{}",
            new { controller = "Home", action = "Pagenotfound" }
        );
}

我的意思是,当我运行项目并输入错误的地址时,它显示默认的 404 页面而不是我设计的页面 - Pagenotfound.cshtml

如果你能帮助我,我真的很感激。

【问题讨论】:

    标签: asp.net-mvc error-handling http-status-code-404 routeconfig


    【解决方案1】:

    在 web.config 页面中的 标记之间复制并粘贴以下代码。当发生 404 错误时,它会重定向到 Pagenotfound.cshtml 页面。

    <customErrors mode="On">
      <error statusCode="404" redirect="/Error/Pagenotfound"/>
    </customErrors>
    

    另外,在控制器页面顶部添加 [HandleError] 属性。

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 2010-10-11
      • 2010-09-11
      • 2011-04-03
      • 2016-06-05
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      相关资源
      最近更新 更多