Asp.Net Tutorial : Custom 404 error Setting in web.config

Leave a Comment

Exposing errors to end users isn’t a good idea, from both a usability and a security point of view. Error handling implemented the right way will help administrators to inspect the complete error, and will provide the casual user with a more useful courtesy page.

ASP.NET gives you control over errors, letting you choose from three options:

  1. Always show errors
  2. Never show errors
  3. Show errors only when the request is coming from the same machine that’s running the application


Following code comes from a typical web.config and demonstrates each of these options:
<configuration>
  <system.web>
      <customErrors mode="On" defaultRedirect="CustomPage.htm" />
  </system.web>
</configuration>

You want to avoid full error disclosure to normal users but display the full error to administrators.

To implement such a personalized view, we need to write a custom HttpModule like the one shown in the following listing.
namespace ASPNET4InPractice.
{
public class ErrorModule: IHttpModule
{
...
public void Init(HttpApplication context)
{
context.Error+=new EventHandler(OnError);
}
void OnError(object sender, EventArgs e)
  {
  HttpApplication app = (HttpApplication)sender;
  HttpException ex = app.Server.GetLastError() as HttpException;
if (app.User.IsInRole(AdministrativeRole))
   {
     app.Response.Clear();
     app.Response.TrySkipIisCustomErrors = true;
     app.Response.Write(string.Format("<h1>This error is only visible" + " to '{0}' members.</h1>", AdministrativeRole));
     app.Response.Write(ex.GetHtmlErrorMessage());
     app.Context.ApplicationInstance.CompleteRequest();
     }
  }
}
}

You can easily adapt this code to integrate more logging instrumentations, like form variables or application status. To register the module, you have to place this configuration in your web.config:
<configuration>
<appSettings>
<add key="admnistrativeRole" value="admin"/>
</appSettings>
<system.web>
<httpModules>
      <add name="CustomErrorModule" type="ASPNET4InPractice.Chapter15.ErrorModule, App_Code"/></httpModules>
<customErrors mode="On" defaultRedirect="ErrorPage.htm" />
</system.web>
</configuration>

0 comments:

Post a Comment