ASP.NET Secrets, Part 4, Page 2
Hiding Error Code from Your Clients
One of the most beautiful features of ASP.NET is its rich error reporting. When something goes wrong, it highlights the exact lines of offending code, provides an explanation of the problem, and if it's feeling merry, even suggests a solution from time to time.
The problem is: You really don't want your visitors viewing code behind your applications. For a start, it may breach your site security. For seconds, it's just not pretty. So, how do you stop it from happening?
First off, stop telling VS.NET to create the debug file, containing a copy of your code. You can do this by altering the application mode from 'Debug' to 'Release'. Use either the drop-down box on the standard VS.NET menu for this, or select Build, Configuration Manager and edit through the dialog box. Next, turn off debugging by editing the Web.config file so the <compilation> element reads <compilation debug="false" />.
Well, that may stop your code from appearing, but it won't get rid of those awful generic error pages. You can, however, replace them with your own, slightly more elegant apologies. Simply alter the <customErrors> element in Web.config to something like <customErrors mode="On" defaultRedirect="genericerror.aspx" />. No problem!
Top Tip: With a defaultRedirect, ASP.NET automatically passes the filename of the page that generated the error in the query string, as a parameter called "aspxerrorpath". You may wish to use this in your error page, perhaps to suggest a user solution or log to an errors file.
Caption: Our edited Web.config file
Forget 404: Customising Your Page Not Found
In the last tip, we discovered how to stop your code being displayed when an error occurs. We also found out how to redirect the user to a certain page when such problems arise. Well, this also kicks in with such irritations as the dreaded "404, Page Not Found" error message.
In those situations where a requested page is not found on the Web server, you might want to display your own custom message rather than a generic error message. You can do that easily, just by expanding the <customErrors> element of your Web.config file.
The following snippet shows part of an edited Web.config file that redirects to genericerror.aspx when regular errors occur, or 404.html when a file not found occurs, or 403.html when a permission denied server error occurs.
<configuration> <system.web> ... <customErrors mode="On" defaultRedirect="genericerror.aspx"> <error statusCode="404" redirect="404.html" /> <error statusCode="403" redirect="403.html" /> </customErrors> ... </system.web> </configuration>
Caption: Error 404 redirection kicking in when I access a non-existent page