简体   繁体   中英

How to handle 404 error on server in asp.net

I have use below code:

<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>

The above code is working fine in localserver but when uploading on the server then 404 exceptions is not redirected to the error page.

I get below Error in server: 在此处输入图片说明

create this methode in 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM