How to not use DeveloperExceptionPageMiddleware

Viewed 663

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?

2 Answers

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. Do not use development environment

  3. 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 ) work.

The easiest way to skip DeveloperExceptionPageMiddleware is not using the Development environment.

You can modify the Properties/launchSettings.json file, change ASPNETCORE_ENVIRONMENT to anything but Development.

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:43562",
      "sslPort": 44332
    }
  },
  "profiles": {
    "api1": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7109;http://localhost:5111",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "MyDevelopment"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "MyDevelopment"
      }
    }
  }
}

In your app, change all builder.Environment.IsDevelopment() to builder.Environment.IsEnvironment("MyDevelopment").

Related