【问题标题】:How to return a 404 from ASP.NET Core exception middleware?如何从 ASP.NET Core 异常中间件返回 404?
【发布时间】:2021-07-13 19:20:57
【问题描述】:

我的应用程序使用自定义 NotFoundException,并且我正在使用 ASP.NET 核心异常处理程序中间件来拦截异常并返回 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);
        });
      });
      ...
  }

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

System.Net.Http.HttpRequestException: 'Error while copying content to a stream.'

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

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

在我将目标框架从 netcoreapp3.1 更改为 net5.0 之前,此 404 代码一直有效。在以 net5.0 为目标时,为了从异常中间件成功返回带有 JSON 的 404,我需要进行哪些更改?

【问题讨论】:

  • 我添加了 services.AddExceptionHandler(options => options.AllowStatusCode404Response = true);这并没有解决它。但是,您的评论确实使我找到了实际的解决方法。

标签: asp.net-core asp.net-core-5.0


【解决方案1】:

问题似乎从this update 转移到了ExceptionHandlerMiddleware。

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

await context.Response.CompleteAsync();

然而,这条线并没有修复我使用 TestServer 的测试,因为 TestServer does not yet implement CompleteAsync。

【讨论】:

  • 谢谢尼克!这导致了 XMLHttpRequest(以及扩展 axios)的一些古怪行为。这只是 404 的问题。其他状态代码工作正常。我认为管道中还发生了一些其他 404 处理,这些处理会破坏响应流,但以对调试工具不透明的方式进行。
猜你喜欢
  • 2019-03-08
  • 2020-04-05
  • 2021-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
  • 2020-04-28
相关资源
最近更新 更多