如何不使用 DeveloperExceptionPageMiddleware

How to not use DeveloperExceptionPageMiddleware

使用 ASP.NET Core 6.0 的新模板时,其中包括 var builder = WebApplication.CreateBuilder(args); DeveloperExceptionPageMiddleware 会自动添加。我不想使用这个中间件,这样我就可以在所有环境中提供一致的错误响应。

有没有办法把我的自定义错误处理放在这个中间件之前,或者阻止它被包含?还是在包含后将其删除?

目前您无法在开发环境的最小托管模型中禁用 DeveloperExceptionPageMiddleware,因为它 is set up 没有任何配置选项。所以选项是:

  1. Use/switch 回到 generic host model(带有 Startup 的那个)并跳过 UseDeveloperExceptionPage 调用。

  2. 不使用开发环境

  3. 设置自定义异常处理。 DeveloperExceptionPageMiddleware 依赖于稍后未在管道中处理异常的事实,因此在构建应用程序后立即添加自定义异常处理程序应该可以解决问题:

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...
    }
});

使用 custom exception handler pageUseExceptionHandler 也应该(除非处理程序本身抛出)工作。

跳过 DeveloperExceptionPageMiddleware 的最简单方法是不使用 Development environment

您可以修改 Properties/launchSettings.json 文件,将 ASPNETCORE_ENVIRONMENT 更改为 任何内容 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"
      }
    }
  }
}

在您的应用中,将所有 builder.Environment.IsDevelopment() 更改为 builder.Environment.IsEnvironment("MyDevelopment")