【问题标题】:Customer Error in Asp.net MVC web.configAsp.net MVC web.config 中的客户错误
【发布时间】:2017-12-23 01:43:07
【问题描述】:

在我的 MVC Web 应用程序中,我需要一个 404 页面来解决所有错误。我正在编辑这行的 web.config 文件:

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

它有效,但在浏览器 url 中我看到 URL/error/404。如何查看被调用的 URL?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    customErrors 节点实际上比httpErrors 更老,所以试试这个。确保在 web.config 中有这些节点作为 system.webServer 节点的子节点:

    <httpErrors>
      <error statusCode="404" path="/error/404" responseMode="ExecuteURL" />
    </httpErrors>
    

    或者,您可以使用customErrors 以两种方式执行此操作: 一是修改个别error节点,二是更改customErrors节点。我不记得其中一个现在是否已过时,但请随意尝试两者。

    <error statusCode="404" path="/error/404" responseMode="ExecuteURL"/>
    

    <customErrors mode="On" redirectMode="ResponseRewrite">
    

    如果上述方法不起作用,则会出现其他问题。你检查过 IIS 日志吗?

    链接

    httpErrors Documentation

    Custom Errors Element documentation(已存档)

    【讨论】:

    • 嗨,尝试这两种解决方案,但没有解决我的问题。当我尝试example.com/1234 (并且我没有路由)时,服务器以运行时错误响应并且没有重定向错误到错误/404 路由。如果我尝试example.com/1234/123(两个参数),这是通过路由拦截,传递控制器并重定向到错误/404(因为如果找不到页面,控制器操作中有一个重定向),这是主控制器中的一个路由。谢谢
    • 我在 global.asax 中使用 Application_error 部分解决。
    【解决方案2】:

    我在 global.asax 中使用 Application_error 部分解决。我添加了这个方法

        protected void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();
            var httpException = exception as HttpException;
            if (httpException != null && httpException.GetHttpCode() == 404)
            {
                Response.Clear();
                Server.ClearError();
                Response.TrySkipIisCustomErrors = true;
    
                IController controller = new CommonController();
    
                var routeData = new RouteData();
                routeData.Values.Add("controller", "Common");
                routeData.Values.Add("action", "PageNotFound");
    
                var requestContext = new RequestContext(
                     new HttpContextWrapper(Context), routeData);
                controller.Execute(requestContext);
    
            }
           }
    

    这很好。问题来自控制器:.i.e.如果我没有找到数据库记录,我想返回一个带有默认错误页面的 404 错误。我还想在浏览器中显示名为 url 的原始 URL,而不是重定向 url。使用返回视图();在控制器中,这不会发生。我该如何解决?谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 2014-12-03
      • 2012-08-23
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多