自定义错误页面,当发生 Http 错误而不更改 url 时

2024-02-27

当 Http 错误发生时,如何在不更改 url 的情况下显示自定义错误页面。

当发生 Http 错误时,如何显示客户自定义错误页面而不路由到另一个 URL。


下面的方法不会使用重定向 - 它将返回您的自定义错误 + 正确的 httpstatus 代码作为对客户端的立即响应,方法是捕获 application_error 方法中的错误,然后选择在同一响应中返回的内容,从而无需重定向。

创建一个 ErrorController - 这允许您定制最终用户错误页面和状态代码。:

[AllowAnonymous]
public class ErrorController : Controller
{
    public ActionResult PageNotFound()
    {
        Response.StatusCode = 404;
        return View();
    }

    public ActionResult ServerError()
    {
        Response.StatusCode = 500;
        return View();
    }

    public ActionResult UnauthorisedRequest()
    {
        Response.StatusCode = 403;
        return View();
    }

    //Any other errors you want to specifically handle here.

    public ActionResult CatchAllUrls()
    {
        //throwing an exception here pushes the error through the Application_Error method for centralised handling/logging
        throw new HttpException(404, "The requested url " + Request.Url.ToString() + " was not found");
    }
}

添加一个路由以捕获所有 url 到路由配置的末尾 - 这将捕获所有尚未通过匹配现有路由捕获的 404:

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

在你的 global.asax 中:

protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();

        //Error logging omitted

        HttpException httpException = exception as HttpException;
        RouteData routeData = new RouteData();
        IController errorController = new Controllers.ErrorController();
        routeData.Values.Add("controller", "Error");
        routeData.Values.Add("area", "");
        routeData.Values.Add("ex", exception);

        if (httpException != null)
        {
            //this is a basic exampe of how you can choose to handle your errors based on http status codes.
            switch (httpException.GetHttpCode())
            {
                case 404:
                    Response.Clear();

                    // page not found
                    routeData.Values.Add("action", "PageNotFound");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

                    break;
                case 500:
                    // server error
                    routeData.Values.Add("action", "ServerError");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
                 case 403:
                    // server error
                    routeData.Values.Add("action", "UnauthorisedRequest");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
                 //add cases for other http errors you want to handle, otherwise HTTP500 will be returned as the default.
                default:
                    // server error
                    routeData.Values.Add("action", "ServerError");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
            }
        }
        //All other exceptions should result in a 500 error as they are issues with unhandled exceptions in the code
        else
        {
            routeData.Values.Add("action", "ServerError");
            Server.ClearError();
            // Call the controller with the route
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自定义错误页面,当发生 Http 错误而不更改 url 时 的相关文章

随机推荐

  • 消除作为模板参数传递的重载成员函数指针的歧义

    我正在尝试重新创建观察者模式我可以完美地将参数转发给观察者的给定成员函数 如果我尝试传递一个地址成员函数其中有多次覆盖 它无法根据参数推导出正确的成员函数 include
  • python的跨平台usb模块?

    我有兴趣在 python 中使用 USB 设备进行一些跨平台工作 关于可以执行此类操作的模块有任何提示或建议吗 我浏览了 SF 和 googlecode 但运气不佳 thanks ct PyUSB http pyusb berlios de
  • QPainterPath 与直线的交点(通过 x 求 QPainterPath y)

    我有 QPainterPath 我需要通过 x 找到 QPainterPath 的 y 坐标 我在 QPainterPath 中找到了 intersected 方法 因此 我创建了新的 QPainterPath 它是具有 x 坐标的从路径边
  • 如何使用java获取weka中的最近邻居

    我一直在尝试使用与 weka 机器学习库一起使用的 Ibk 最近邻算法 我知道如何对实例进行分类 但我想实现协同过滤功能 因此我需要实际获取最接近感兴趣对象的实际对象列表 在 weka 中我实际上该如何使用它的 java API 来做到这一
  • 在Erlang中如何获取客户端的ip和端口?

    在下面的代码中 服务器正在侦听端口 2345 接受客户端的连接后 它返回 ok Socket start gt ok Listen gen tcp listen 2345 binary packet 4 reuseaddr true act
  • 如何在继续之前等待经过dispatch_async?

    我正在执行一系列的dispatch async 我只想在它们全部完成后更新UI 问题是dispatch async 中的方法在单独的线程中调用某些内容 因此它会在数据完全加载之前返回 并且在加载所有内容之前调用dispatch group
  • PHP-正则表达式检查字符串是否有中文字符

    我有字符串 str我想检查它的内容是否有汉字 true false str 赕就可消垻 只有当所有方块都被消垻时才可以过关 你能帮我么 谢谢 阿德里安 您可以使用 unicode 字符类http www regular expression
  • 求解三次方程以找到曲线上距某点最近的点

    Ok 我有一个射弹 其位置定义为 a x initialX initialDX time a y initialY initialDY time 0 5 gravtiy time 2 我希望能够预测该射弹将与我的环境中的哪些障碍物发生碰撞
  • 如果未在命令行上指定,则仅在 psql-script 中设置变量

    我想给option在命令行上为我的 psql 脚本指定一些变量 psql v myVar myValue 但是我发现无法在 sql 脚本本身中为这些变量提供默认值 语法 set MyVar defaultValue 覆盖值myValue在
  • 在python中将一维列表转换为具有给定行长度的二维列表[重复]

    这个问题在这里已经有答案了 有没有一种简单的方法可以将一维列表转换为具有给定行长度的二维列表 假设我有一个这样的列表 myList 1 2 3 4 5 6 7 8 9 我想将上面的列表转换为 3 x 3 的表格 如下所示 myList 1
  • 测量查询性能:“执行计划查询成本”与“所用时间”

    我正在尝试确定两个不同查询的相对性能 并且有两种可用的方法来衡量它 1 运行两个查询并对每个查询计时2 运行两者并从实际执行计划中获取 查询成本 这是我运行的用于计时查询的代码 DBCC FREEPROCCACHE GO DBCC DROP
  • msi 安装程序运行两次

    我有一个通过 msi 安装的程序 msi 是使用 VS2008 部署项目构建的 并具有在安装完成后运行该程序的自定义操作 一旦 msi 运行 我可以简单地更新版本号 生成新的产品代码 并且 msi 可以在同一台 PC 上再次运行 但是 我想
  • Fancybox 宽度不适用

    使用以下 JS 宽度不会被调整 我使用的时候没有调整 750 or 750px a city prompt fancybox width 750 我已经发布在fancybox http fancybox net api论坛讨论过这个问题 但
  • Magento 扁平化产品

    尝试启用并重新索引产品平面数据时 从 magento 收到错误 平面目录模块的可过滤和 或可排序限制为 64 个 属性 目前有521个 请减少数量 可过滤 可排序的属性以便使用此模块 我不明白这意味着什么以及 magento 从哪里获取这个
  • 为什么选择下拉菜单不允许我单击某个项目 IE,但在 Firefox、Chrome 等中却可以正常工作?

    我正在使用jquery mega下拉菜单插件 http www designchemical com lab jquery mega drop down menu plugin examples 在其中一个菜单中 我想添加一个下拉框 它在
  • 如何在flutter中分割dart类?

    我做了以下测试 但它不起作用 main dart class Test static const a 10 final b 20 final c a 1 part dart part of main dart class Test fina
  • 如何在 Fortran 中将子例程名称作为参数传递?

    将子例程名称作为参数传递的语法是什么 示意图 call action mySubX argA argB subroutine action whichSub argA argB call subroutine whichSub argA a
  • 嵌入式 Tomcat 不提供静态内容

    我正在使用以下内容 基于this https stackoverflow com questions 640022 howto embed tomcat 6 创建嵌入式 Tomcat 服务器 File catalinaHome new Fi
  • 在 Delphi 7 中,我可以设置“调试”和“发布”模式吗?

    在大多数现代 IDE 中 您可以拥有 调试 和 发布 构建配置 并且可以在它们之间快速切换 在Delphi 7中 这似乎不可能 我必须进入项目设置并手动切换优化和所有调试信息 如果有一个插件或类似的插件可以帮我处理这个问题 那就太好了 有人
  • 自定义错误页面,当发生 Http 错误而不更改 url 时

    当 Http 错误发生时 如何在不更改 url 的情况下显示自定义错误页面 当发生 Http 错误时 如何显示客户自定义错误页面而不路由到另一个 URL 下面的方法不会使用重定向 它将返回您的自定义错误 正确的 httpstatus 代码作