404 and 403 Error Pages in ASP.NET

January 12, 2009 | By

The 2 most common HTTP errors that occur are the 404 and 403. 404 is the File Not Found error and it is generated when the user clicks on a broken link or enters a file or folder name that does not exist in the server. And the 403 Access Denied error is generated when the user tries to access a page he/she has no permissions to. These errors can be handled by IIS or the ASP.NET website, here I will show the latter.

To start handling these errors, 3 pages need to be created in the root folder of the project, one for each error and the last one will be displayed when an unhandled error occurs. Its always better to keep the code in these pages to a minimum and dont access databases, the file system, or any external pages. And the last thing to make sure of is anonymous users have access to these pages.

To use them, they should be included in the web.config file, in the element. The mode attribute is required, and it sets whether the custom errors are enabled or not. Its third option is RemoteOnly and this will display the custom page to remote users only, i.e. if the website is accessed from the local host the customErrors element will not work. The defaultRedirect attribute sets the page that will displayed if the error occurred is not a 404 or a 403 error.

Filed in: ASP.NET | Tags: , ,

Comments (3)

  1. In my case, the noaccess.aspx page is never displayed. Rather the the user is prompted with the login page. If user logins successfully with the authorized account, she will be redirected to the page, otherwise the login page continues to prompt.

    I even tried to catch access denied case from the global.asax page, but no success. I don’t why this happens. Currently I am catching all these in the login page and then redirect the user to the access denied page [noaccess.aspx].


  2. Hey sangem, what I understood from your comment is you created the whole project in 1 folder and restricted access to logged in users only. If this is the case, the easiest way to solve this problem is to create a sub folder and put in it all the pages that require logging in. And leave the login and noaccess pages in the root folder. Then restrict access to the sub folder using ASP.NET’s Configuration web app. This way anonymous users can browse the whole website except the restricted folder. Please try it out and let me know what happens.

  3. KalC

    I ran into the same problem as Sangam… and Amgad’s solution solved the problem. Thanks.