DEV Community

davinceleecode
davinceleecode Subscriber

Posted on • Edited on

Custom Error Pages in ASP.NET (Web.config)

Here's how to properly configure custom error pages, including 404s and static file handling.


✅ 1. Enable Custom Errors in web.config

<configuration>
  <system.web>
    <customErrors mode="On" defaultRedirect="~/ErrorPages/GeneralError.html">
      <error statusCode="404" redirect="~/ErrorPages/404.html" />
      <error statusCode="500" redirect="~/ErrorPages/500.html" />
    </customErrors>
  </system.web>
</configuration>
Enter fullscreen mode Exit fullscreen mode

📘 customErrors mode Options

Mode Description
Off Shows full error details, including stack trace. Use this only in development.
On Always shows the custom error page defined, even on the local machine.
RemoteOnly Shows detailed error to local requests, and custom page to remote users. Ideal for dev.
🔐 Tip: In production, use On or RemoteOnly to hide sensitive error details.
Enter fullscreen mode Exit fullscreen mode

🧱 2. Handle Static File Errors (IIS Level)

By default, IIS handles static file errors (e.g., missing .jpg) and bypasses ASP.NET. To handle those too:
Add this under system.webServer:

<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="404" path="/ErrorPages/404.html" responseMode="ExecuteURL" />
  </httpErrors>
</system.webServer>
Enter fullscreen mode Exit fullscreen mode

Explanation of httpErrors attributes:
errorMode="Custom": Enables your custom error pages.
existingResponse="Replace": Overwrites the existing IIS error with your own.
responseMode="ExecuteURL": Executes an ASP.NET page or serves a static file.

🎯 Example Folder Structure

/ErrorPages/
  ├── 404.html
  ├── 500.html
  └── GeneralError.html
Enter fullscreen mode Exit fullscreen mode

Make sure these files are included in your project and set to "Copy if newer".

Summary

Task Configuration Section
ASP.NET runtime errors in system.web
Static file errors (e.g., 404) in system.webServer
Show detailed errors locally mode="RemoteOnly"
Catch-all fallback mode="defaultRedirect"

If you're using MVC, you can create a custom ErrorController to catch all unhandled errors programmatically.

If you found this helpful, consider supporting my work at ☕ Buy Me a Coffee.

Top comments (0)