0

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

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

4

2 回答 2

1

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

  1. 使用/切换回通用主机模型(带有Startups 的模型)并跳过UseDeveloperExceptionPage调用。

  2. 设置自定义异常处理。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...
    }
});

使用自定义异常处理程序页面UseExceptionHandler应该(除非处理程序本身抛出)工作。

于 2021-11-16T07:54:43.550 回答
0

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").

于 2021-12-04T11:55:51.093 回答