小编Nic*_*nce的帖子

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

我的应用程序使用自定义 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)

asp.net-core asp.net-core-5.0

4
推荐指数
1
解决办法
3607
查看次数

标签 统计

asp.net-core ×1

asp.net-core-5.0 ×1