如何处理ASP.NET中服务器上的404错误

时间:2019-02-08 09:07:33

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

我使用了以下代码:

<customErrors mode="On" defaultRedirect="~/ErrorPage/Default.aspx">
      <error statusCode="403" redirect="~/ErrorPage/Default.aspx"/>
      <error statusCode="404" redirect="~/ErrorPage/Default.aspx"/>
      <error statusCode="400" redirect="~/ErrorPage/Default.aspx"/>
      <error statusCode="500" redirect="~/ErrorPage/Default.aspx"/>
</customErrors>

上面的代码在localserver上运行正常,但是在服务器上上传时,404异常不会重定向到错误页面。

我低于服务器错误: enter image description here

1 个答案:

答案 0 :(得分:0)

在global.asax中创建此方法

    public void Application_Error()
    {
    var routeData = new RouteData();
        routeData.Values.Add("controller", "yourControllerNameForError");
        routeData.Values.Add("action", "YourActionMethodeForError");

        if (exception is HttpException httpException)
        {              
            switch (httpException.GetHttpCode())
            {
                case 404:            
                    routeData.Values["action"] =  "Your404MethodeError";
                    break;                 
            }
        }

        Server.ClearError();
        Response.TrySkipIisCustomErrors = true;
        IController errorController = new ErrorController();
        errorController.Execute(new System.Web.Routing.RequestContext (
             new HttpContextWrapper(Context), routeData));
}