Mastering HTTP Status Code Handling with UseStatusCodePages() in .NET

Effective error handling is crucial for creating robust and user-friendly web applications. .NET provides several built-in tools to help you manage errors gracefully, one of which is the UseStatusCodePages() middleware. This middleware allows you to handle HTTP status codes with custom responses, ensuring a consistent and informative user experience.

Why Use UseStatusCodePages()?

By default, an ASP.NET Core app doesn't provide a status code page for HTTP error status codes, such as 404 - Not Found. When the app sets an HTTP 400-599 error status code that doesn't have a body, it returns the status code and an empty response body. To enable default text-only handlers for common error status codes, call UseStatusCodePages in Program.cs.

Getting Started with UseStatusCodePages()

Adding status code pages middleware to your .NET application is straightforward. Here's how you can get started.

Basic Usage

To enable status code pages middleware, add UseStatusCodePages() to your middleware pipeline in the Program.cs file.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

// added
app.UseStatusCodePages();

app.MapControllers();

app.Run();

Customizing the Response

You can customize the responses for different status codes in several ways.

Text Responses

Display a custom text message for any status code.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.UseStatusCodePages("text/plain", "Status code page, status code: {0}");

app.MapControllers();

app.Run();

Redirect Responses

Redirect to a custom error page based on the status code.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.UseStatusCodePagesWithRedirects("/error/{0}");

app.MapControllers();

app.Run();

Handle these redirects in your controller.

[Route("error/{statusCode}")]
public IActionResult Error(int statusCode)
{
    var viewName = statusCode == 404 ? "NotFound" : "Error";
    return View(viewName);
}

Re-execute the Request

Re-execute the request pipeline for a specific path, allowing you to handle the error within your application.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.UseStatusCodePagesWithReExecute("/error/{0}");

app.MapControllers();

app.Run();

This method re-executes the request, enabling you to use the same middleware pipeline to handle the error.

Benefits of UseStatusCodePages()

  • Centralized Error Handling: Manage all errors from a single point, reducing complexity and improving maintainability.
  • User-Friendly Responses: Provide clear and helpful error messages, improving the overall user experience.
  • Flexible Customization: Tailor the error handling to suit your application's needs, whether through simple text responses, redirects, or re-executing the request pipeline.

Conclusion

Implementing UseStatusCodePages() in your .NET application enhances error handling by providing a consistent, user-friendly response to HTTP status codes. Whether you opt for simple text messages, custom redirects, or re-executing requests, this middleware ensures your application handles errors gracefully and efficiently.


Recommended Free Ebook
Similar Articles