Keywords: ASP.NET MVC 4 | Custom Error Pages | ErrorController | web.config Configuration | IIS Error Handling
Abstract: This article provides a comprehensive solution for configuring custom error pages in ASP.NET MVC 4. By analyzing real-world problems from Q&A data and incorporating technical depth from reference articles, it offers specific implementation methods for handling 500, 404, and 403 errors. The content covers web.config configuration, ErrorController design, view implementation, and IIS integration, while explaining why HandleErrorAttribute only processes 500 errors. Through comparison of different configuration approaches, it provides best practices for deploying custom error pages in production environments.
Problem Analysis and Background
Configuring custom error pages is a common but error-prone task in ASP.NET MVC 4 development. As evident from the Q&A data, developers frequently encounter the issue where 500 errors display custom pages correctly, but 404 and 403 errors fail to work properly. The root cause lies in ASP.NET MVC's layered error handling architecture, where different components handle errors at different levels.
Limitations of HandleErrorAttribute
The HandleErrorAttribute class mentioned in the Q&A data indeed only handles 500-series errors. Analysis of its source code reveals that this attribute only triggers when unhandled exceptions are thrown in controller actions, while 404 and 403 errors typically don't involve exception throwing but are implemented through HTTP status code setting. This explains why custom CustomHandleErrorAttribute cannot handle non-500 errors.
Complete Solution Architecture
To comprehensively solve custom error page issues, a layered processing strategy is required:
1. ErrorController Design
As shown in the best answer, creating a dedicated ErrorController is central to solving this problem. This controller handles various types of errors and returns appropriate views:
public class ErrorController : Controller
{
public ViewResult Index()
{
return View("Error");
}
public ViewResult NotFound()
{
Response.StatusCode = 404;
return View("NotFound");
}
public ViewResult Unauthorized()
{
Response.StatusCode = 403;
return View("UnauthorizedAccess");
}
}
2. web.config Configuration Optimization
Proper web.config configuration must consider error handling at both ASP.NET and IIS levels:
<system.web>
<customErrors mode="On" defaultRedirect="~/Error" redirectMode="ResponseRewrite">
<error statusCode="403" redirect="~/Error/Unauthorized" />
<error statusCode="404" redirect="~/Error/NotFound" />
<error statusCode="500" redirect="~/Error" />
</customErrors>
</system.web>
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404" />
<remove statusCode="403" />
<remove statusCode="500" />
<error statusCode="404" path="404.html" responseMode="File" />
<error statusCode="403" path="403.html" responseMode="File" />
<error statusCode="500" path="500.html" responseMode="File" />
</httpErrors>
</system.webServer>
3. View Implementation Details
Custom error page views must properly handle model binding and debug information display:
@model System.Web.Mvc.HandleErrorInfo
@{
Layout = "_Layout.cshtml";
ViewBag.Title = "Error";
}
<div class="list-header clearfix">
<span>Error</span>
</div>
<div class="list-sfs-holder">
<div class="alert alert-error">
An unexpected error has occurred. Please contact the system administrator.
</div>
@if (Model != null && HttpContext.Current.IsDebuggingEnabled)
{
<div>
<p>
<b>Exception:</b> @Model.Exception.Message<br />
<b>Controller:</b> @Model.ControllerName<br />
<b>Action:</b> @Model.ActionName
</p>
<div style="overflow:scroll">
<pre>
@Model.Exception.StackTrace
</pre>
</div>
</div>
}
</div>
Key Configuration Parameter Analysis
Importance of redirectMode
The redirectMode="ResponseRewrite" parameter is crucial. When set to ResponseRedirect, ASP.NET performs a 302 redirect, which changes the URL and returns a 200 status code, severely impacting SEO and user experience. ResponseRewrite maintains the original URL while only replacing the response content.
IIS vs ASP.NET Error Handling Division
The reference article clearly states that IIS handles static file errors and requests that don't match routing rules, while ASP.NET handles dynamic content errors. This division requires configuration at both levels:
- ASP.NET level: Handles controller and action-related errors
- IIS level: Handles static files, routing mismatches, and other errors
Production Environment Best Practices
Error Mode Settings
In production environments, the following configurations are recommended:
<customErrors mode="RemoteOnly" />
<httpErrors errorMode="DetailedLocalOnly" />
Use of Static Files
For IIS error pages, static HTML files are recommended over ASPX pages. This ensures that custom error pages can still be displayed even if the ASP.NET application experiences critical errors.
Common Issue Troubleshooting
Incorrect Status Codes
If custom error pages return incorrect status codes, explicitly set them in the corresponding ErrorController methods:
Response.StatusCode = 404; // or other appropriate status code
Content Type Issues
When using static HTML files as error pages, ensure IIS correctly sets MIME types. For ASPX pages, ASP.NET automatically handles content types.
Performance Considerations
When implementing custom error pages, performance impacts should be considered:
- Avoid complex database queries in error pages
- Minimize error page size and loading time
- Consider caching strategies to improve error page response speed
Conclusion
By adopting the ErrorController approach combined with layered configuration strategy, comprehensive solutions for custom error page issues in ASP.NET MVC 4 can be achieved. The key is understanding that different errors are handled by different components and properly configuring both ASP.NET and IIS levels. This approach not only solves display issues for 500, 404, and 403 errors but also ensures correct HTTP status codes and good user experience.