Home > Enterprise >  How to not use DeveloperExceptionPageMiddleware
How to not use DeveloperExceptionPageMiddleware

Time:11-17

When using the new template for ASP.NET Core 6.0, which includes var builder = WebApplication.CreateBuilder(args); the DeveloperExceptionPageMiddleware is automatically added. I would like to not use this middleware so that I can provide a consistent error response in all environments.

Is there anyway to put my custom error handling before this middleware, or prevent it from being included? Or to remove it after it's been included?

CodePudding user response:

Currently you can't disable DeveloperExceptionPageMiddleware in minimal hosting model for development environment since it is set up without any options to configure. So options are:

  1. Use/switch back to generic host model (the one with Startups) and skip the UseDeveloperExceptionPage call.

  2. Setup custom exception handling. DeveloperExceptionPageMiddleware relies on the fact that exception was not handled later down the pipeline so adding custom exception handler right after the building the app should do the trick:

app.Use(async (context, func) =>
{
    try
    {
        await func();
    }
    catch (Exception e)
    {
        context.Response.Clear();

        // Preserve the status code that would have been written by the server automatically when a BadHttpRequestException is thrown.
        if (e is BadHttpRequestException badHttpRequestException)
        {
            context.Response.StatusCode = badHttpRequestException.StatusCode;
        }
        else
        {
            context.Response.StatusCode = 500;
        }
        // log, write custom response and so on...
    }
});

Using custom exception handler page with UseExceptionHandler also should (unless the handler itself throws

  • Related