Saturday 28 November 2020

ASP.Net 404 page not found error handle

 



When a URL hits and if page is not found on the server then ASP.Net throws a 404 page not found exception. If 404 page not found exception handled properly then you will get the default error page by ASP.Net , Which doesn't looks good and user friendly. 404-page handling is considered as a good practice of web development. Paste the following code on Global asax file and you will be redirected to your custom error page. 

Global Asax

Library Link : System.Net

protected void Application_Error(object sender, EventArgs e)

        {

            Exception lastErrorInfo = Server.GetLastError();

            Exception errorInfo = null;

 

            bool isNotFound = false;

            if (lastErrorInfo != null)

            {

                errorInfo = lastErrorInfo.GetBaseException();

                var error = errorInfo as HttpException;

                if (error != null)

                    isNotFound = error.GetHttpCode() == (int)HttpStatusCode.NotFound;

            }

            if (isNotFound)

            {

                Server.ClearError();

                Response.Redirect("~/Common/page404");// Do what you need to render in view

            }

        }

Next Topic

No comments:

Post a Comment