Certainly! ASP.NET MVC Custom Error Pages are an essential part of developing a user-friendly, robust web application. These pages allow developers to provide a more polished and less intimidating user experience when errors occur. Instead of displaying generic, technical error messages, custom error pages can guide users on what to do next or provide a branded appearance that aligns with the application's identity. Here, you'll learn how to set up custom error pages in an ASP.NET MVC application step-by-step.
Step 1: Basic Understanding of Error Pages in ASP.NET MVC
Before diving into custom error pages, it's crucial to understand what ASP.NET MVC provides out of the box. When an error occurs during a request, ASP.NET MVC automatically returns an error response to the client. These error responses are generally in the form of HTTP status code (e.g., 404, 500) and might not always be user-friendly.
ASP.NET MVC offers different modes of error handling, but for custom error pages, the configuration typically involves modifying the web.config file and adding specific controllers and views.
Step 2: Modifying Web.config to Enable Custom Errors
The primary change to make custom error pages work is in the web.config
file, where you configure the application to use custom error pages.
a. Modify <customErrors>
Settings
In the web.config
file, find the <system.web>
section and add or modify the <customErrors>
element. For example:
<system.web>
<customErrors mode="On" defaultRedirect="~/Error/GeneralError">
<error statusCode="404" redirect="~/Error/NotFound"/>
<error statusCode="500" redirect="~/Error/ServerError"/>
</customErrors>
</system.web>
Here's what each attribute means:
mode
: Determines whether custom errors are displayed. Possible values areOn
,Off
, andRemoteOnly
(which shows custom errors to remote users and detailed errors locally).defaultRedirect
: Specifies a URL to redirect to when a custom error does not fit the specificstatusCode
.- Nested
<error>
elements: Define specific redirects for particular HTTP status codes.
b. Modify <httpErrors>
Settings
Starting from IIS 7, you need to configure custom HTTP errors in IIS separately using the <httpErrors>
element:
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404"/>
<error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL"/>
<remove statusCode="500"/>
<error statusCode="500" path="/Error/ServerError" responseMode="ExecuteURL"/>
<remove statusCode="503"/>
<error statusCode="503" path="/Error/ServiceUnavailable" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Step 3: Adding Controller Actions for Error Pages
In order to utilize the URLs specified in the web.config
, create an ErrorController
and corresponding actions that render the custom error pages.
a. Create the Error Controller
Add a new controller to your project named ErrorController
:
using System.Web.Mvc;
namespace YourNamespace.Controllers
{
public class ErrorController : Controller
{
public ActionResult GeneralError()
{
// Additional error handling logic can be added here
return View();
}
public ActionResult NotFound()
{
// Additional error handling logic can be added here
return View();
}
public ActionResult ServerError()
{
// Additional error handling logic can be added here
return View();
}
public ActionResult ServiceUnavailable()
{
// Additional error handling logic can be added here
return View();
}
}
}
Step 4: Creating View Files for Error Pages
Create the corresponding view files for each action defined in the ErrorController
. These views will display the custom error messages to the users.
a. Create the GeneralError
View
Navigate to the Views/Error
directory (create it if it doesn't exist), and add the following content to GeneralError.cshtml
:
@{
ViewBag.Title = "An unexpected error occurred";
}
<div class="error-container">
<h1>Oops! Something went wrong.</h1>
<p>We're sorry, but an error occurred while processing your request.</p>
<button onclick="window.location.href='/'">Return Home</button>
</div>
b. Create the NotFound
View
Add a NotFound.cshtml
view with the following content:
@{
ViewBag.Title = "Page not found";
}
<div class="error-container">
<h1>404 Error: Page not found</h1>
<p>The requested page could not be found on this server.</p>
<button onclick="window.location.href='/'">Return Home</button>
</div>
c. Create the ServerError
View
Add a ServerError.cshtml
view:
@{
ViewBag.Title = "Internal Server Error";
}
<div class="error-container">
<h1>500 Error: Internal Server Error</h1>
<p>There was a problem with the server while processing your request.</p>
<button onclick="window.location.href='/'">Return Home</button>
</div>
d. Create the ServiceUnavailable
View
Add a ServiceUnavailable.cshtml
view:
@{
ViewBag.Title = "Service Unavailable";
}
<div class="error-container">
<h1>503 Error: Service Unavailable</h1>
<p>The server is currently experiencing issues and cannot complete your request.</p>
<button onclick="window.location.href='/'">Return Home</button>
</div>
Step 5: Styling the Error Pages
To ensure that your custom error pages match your application's look and feel, style them using CSS.
a. Add CSS for Styling
Add some CSS to style the error pages. You can place this in your existing CSS file or a separate CSS file (CustomError.css
):
.error-container {
text-align: center;
margin-top: 50px;
}
.error-container h1 {
color: #333;
font-size: 2em;
}
.error-container p {
color: #666;
font-size: 1.1em;
margin-bottom: 20px;
}
.error-container button {
padding: 10px 20px;
background-color: #3498db;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
}
.error-container button:hover {
background-color: #2980b9;
}
Include this CSS file in your layout or directly in your views.
Step 6: Handling Unhandled Exceptions Globally
ASP.NET MVC provides a way to handle unhandled exceptions globally using the Application_Error
method in the Global.asax.cs
file.
a. Implementing Global Error Handling
In the Global.asax.cs
file, find or add the Application_Error
method:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
if (exception != null)
{
// Log the exception details here, e.g., using a logging framework
Server.ClearError();
Response.Redirect("/Error/ServerError");
}
}
This method captures unhandled exceptions that occur during the request lifecycle and redirects users to the ServerError
action in the ErrorController
.
Step 7: Testing the Custom Error Pages
To ensure that your custom error pages are working correctly, deliberately create errors in your application.
a. Testing 404 Not Found Error
Navigate to a URL that does not exist within your application (e.g., https://yourapp.com/nonexistentpage
). If everything is set up correctly, you should be redirected to the NotFound
page.
b. Testing 500 Internal Server Error
Add a route that intentionally causes a server error. For example, create an action method in a controller that throws an exception:
public class TestController : Controller
{
public ActionResult ThrowError()
{
throw new Exception("Intentional exception for testing 500 error");
return View();
}
}
Navigate to this route (e.g., https://yourapp.com/test/throwerror
). The ServerError
page should display.
Step 8: Enhancing the Error Pages
Depending on your application's needs, you can enhance your custom error pages with:
a. User Feedback
Encourage users to report issues. Add a form to each error page that allows them to provide feedback.
b. Error Details for Developers
Provide detailed error information for developers by conditionally showing error details when the application is running in a development environment.
c. Maintenance Notices
Display maintenance notices or messages when your site is undergoing scheduled maintenance.
Conclusion
Custom error pages in ASP.NET MVC are crucial for creating a better user experience. By following this guide, you’ve learned how to configure, create, and style custom error pages for various HTTP status codes. Additionally, by implementing global error handling, you can ensure that your application can gracefully handle unexpected issues.
Remember that creating effective custom error pages involves not only displaying user-friendly messages but also maintaining a consistent brand and guiding users towards a resolution. Happy coding!