1. Configure the application to handle specific HTTP errors (e.g., 404 and 500) using…
- User
- Configure the application to handle specific HTTP errors (e.g., 404 and 500) using the UseStatusCodePagesWithReExecute middleware
- Assistant
To configure an ASP.NET Core application to handle specific HTTP errors such as 404 (Not Found) and 500 (Internal Server Error) using the UseStatusCodePagesWithReExecute middleware, you need to set up error handling in your Startup.cs (or Program.cs if using minimal hosting model) and create error handling endpoints or pages.
Below is a step-by-step example assuming ASP.NET Core 6 or later (minimal hosting model). The approach is similar for earlier versions, but the Startup class is used instead of Program.cs.
First, create MVC controllers or Razor Pages that will handle the errors. For example, create an ErrorsController with actions for status codes:
// Controllers/ErrorsController.cs
using Microsoft.AspNetCore.Mvc;
public class ErrorsController : Controller
{
[Route("Error/{statusCode}")]
public IActionResult HandleErrorCode(int statusCode)
{
if (statusCode == 404)
{
return View("NotFound"); // Views/Errors/NotFound.cshtml
}
if (statusCode == 500)
{
return View("ServerError"); // Views/Errors/ServerError.cshtml
}
return View("GenericError"); // Generic fallback error page
}
}
Make sure you create the corresponding Razor views inside the Views/Errors folder:
NotFound.cshtml for 404.ServerError.cshtml for 500.GenericError.cshtml for other errors.Make sure MVC services are registered:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
Use UseStatusCodePagesWithReExecute middleware before any routing or endpoint middleware, so the status code pages middleware can intercept status codes and re-execute the pipeline on the error endpoint.
if (!app.Environment.IsDevelopment())
{
// You can configure specific environment error handling if needed
app.UseExceptionHandler("/Error/500"); // For unhandled exceptions
}
// Add the status code pages middleware:
app.UseStatusCodePagesWithReExecute("/Error/{0}");
app.UseStaticFiles();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
UseStatusCodePagesWithReExecute("/Error/{0}"): When a status code (like 404 or 500) is detected, the request pipeline is re-executed with the path /Error/{statusCode}, e.g., /Error/404 or /Error/500.ErrorsController handles these routes and returns appropriate views.UseExceptionHandler("/Error/500") middleware handles unhandled exceptions by redirecting to /Error/500.@*
Views/Errors/NotFound.cshtml
*@
@{
ViewData["Title"] = "Page Not Found";
}
<h1>404 - Page Not Found</h1>
<p>The requested page could not be found.</p>
UseStatusCodePagesWithReExecute to catch status codes.UseExceptionHandler for 500 errors from exceptions.If you want a minimal example for .NET 6+ Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error/500");
}
app.UseStatusCodePagesWithReExecute("/Error/{0}");
app.UseStaticFiles();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Let me know if you want help with a non-MVC Razor Pages version or a more detailed example!