如何从 ASP.NET Core 异常中间件返回 404?

Nic*_*nce 4 asp.net-core asp.net-core-5.0

我的应用程序使用自定义 NotFoundException,并且使用 ASP.NET core 异常处理程序中间件来拦截异常并返回 404 响应。

这是中间件的简化版本。

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
      app.UseExceptionHandler(appBuilder => {
        appBuilder.Run(async context => {
          context.Response.StatusCode = (int)HttpStatusCode.NotFound;
          var responseContent = new {
            StatusCode = context.Response.StatusCode,
            Message = "Not found"
          };
          await context.Response.WriteAsJsonAsync(responseContent);
        });
      });
      ...
  }

Run Code Online (Sandbox Code Playgroud)

我希望这段代码返回一个 404 响应,内容为 JSON,但请求只是出错。如果我使用 HttpClient 运行测试,则会收到以下错误:

System.Net.Http.HttpRequestException: 'Error while copying content to a stream.'
Run Code Online (Sandbox Code Playgroud)

如果我将中间件中的状态代码更改为 404 以外的任何代码,它似乎会按预期工作。

// changing this line
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
// to this line will successfully return the result
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
Run Code Online (Sandbox Code Playgroud)

这个 404 代码一直有效,直到我将目标框架从 netcoreapp3.1 更改为 net5.0。在针对 net5.0 时,我需要更改什么才能从异常中间件成功返回带有 JSON 的 404?

Nic*_*nce 7

问题似乎是从这次更新到 ExceptionHandlerMiddleware 的。

添加此行修复了站点实时运行时的响应。

await context.Response.CompleteAsync();
Run Code Online (Sandbox Code Playgroud)

然而,这一行并没有修复我使用 TestServer 的测试,因为 TestServer尚未实现CompleteAsync。