【问题标题】:404 Http error handler in Asp.Net MVC (RC 5)Asp.Net MVC (RC 5) 中的 404 Http 错误处理程序
【发布时间】:2010-09-11 15:35:54
【问题描述】:

如何在框架不抛出 Exception 500 错误代码的情况下处理 404 错误?

【问题讨论】:

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


    【解决方案1】:

    http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx给出如下解释:

    添加通配符路由规则作为最终规则:

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

    任何与其他规则不匹配的请求都会被路由到错误控制器的 Http404 操作,您还需要对其进行配置:

    public ActionResult Http404(string url) {
        Response.StatusCode = 404;
        ViewData["url"] = url;
        return View();
    }
    

    【讨论】:

    • 仅供参考,上面链接的帖子返回了 404(具有讽刺意味)。新地址为:jason.whitehorn.ws/2008/06/17/…
    • 这里唯一的问题是与典型的 /{controller}/{action}/{id} 路由匹配太多。为了解决这个问题,我明确定义了我的所有路线并摆脱了它。
    • 不幸的是,该链接不起作用。即使jason.whitehorn.ws 也无法访问:|
    • 这适用于路由不匹配的情况,但在 id 无效时无济于事......
    • @JasonWhitehorn 404 再次
    【解决方案2】:

    如果请求与控制器匹配,但与操作不匹配,您也可以在控制器中覆盖 HandleUnknownAction。默认实现确实会引发 404 错误。

    【讨论】:

    【解决方案3】:

    throw new HttpException(404, "Resource Not Found");

    【讨论】:

      【解决方案4】:

      使用 MVC 3,您可以返回 HttpNotFound() 以正确返回 404。

      像这样:

      public ActionResult Download(string fontName)
      {
          FontCache.InitalizeFonts();
      
          fontName = HttpUtility.UrlDecode(fontName);
      
          var font = FontCache.GetFontByName(fontName);
          if (font == null)
              return HttpNotFound();
      
          return View(font);
      }
      

      【讨论】:

        猜你喜欢
        • 2014-03-26
        • 2016-06-05
        • 2010-10-17
        • 2013-02-24
        • 2015-05-30
        • 2020-10-18
        • 1970-01-01
        • 1970-01-01
        • 2018-12-08
        相关资源
        最近更新 更多