如何不使用 DeveloperExceptionPageMiddleware

Col*_*lue 10 c# asp.net-core asp.net-core-6.0 .net-6.0

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

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

Gur*_*ron 11

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

  1. 使用/切换回通用主机模型(带有Startups 的模型)并跳过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...
    }
});
Run Code Online (Sandbox Code Playgroud)

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


Wil*_*ang 9

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

您可以修改该Properties/launchSettings.json文件,更改ASPNETCORE_ENVIRONMENTDevelopment.

{
  "$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"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的应用程序中,将全部更改builder.Environment.IsDevelopment()builder.Environment.IsEnvironment("MyDevelopment").