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

时间:2014-09-15 09:18:17

标签: asp.net-mvc asp.net-mvc-3

如何在没有更改网址的情况下发生Http错误时显示自定义错误页面。当发生Http错误时,如何显示客户自定义错误页面而不路由到另一个网址。

2 个答案:

答案 0 :(得分:4)

以下方法不会使用重定向 - 它将返回您的自定义错误+正确的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");
    }
}

添加一条路线以捕获路线配置末尾的所有网址 - 这会捕获所有尚未通过匹配现有路线捕获的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));
        }
    }

答案 1 :(得分:1)

如果系统无法找到请求的网址(状错误控制器,如果系统触发内部服务器错误(状态代码500)

<customErrors>

您必须创建一个包含ServerError和NotFound操作方法的错误控制器,该方法呈现相关视图以向用户显示正确的消息。

<!--<Redirect to error page>-->
<customErrors mode="On" defaultRedirect="~/Error/ServerError">
  <error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
<!--</Redirect to error page>-->

编辑2:

为了在发生自定义错误时保持相同的网址,您需要安装 Magical Unicorn Mvc Error Toolkit 2.2.2 nuget包。

您可以按照以下步骤使用:

  1. 在visual studio中打开解决方案
  2. 转到public class ErrorController : Controller { public ActionResult NotFound() { return View(); } public ActionResult Error() { return View(); } } 菜单,然后选择Tools
  3. 从子菜单中选择Nuget Package Manager
  4. 在程序包管理器控制台中编写Package Manager Console
  5. 你可以visit here for more info关于nuget包

    它将安装将根据您的要求工作的nuget包。