Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a 404 from ASP.NET Core exception middleware?

My application uses a custom NotFoundException, and I'm using the ASP.NET core exception handler middleware to intercept the exception and return a 404 response.

This is a simplified version of the middleware.

  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);
        });
      });
      ...
  }

I expect this code to return a 404 response with the content as JSON, but requests simply error out. If I run a test using HttpClient I get the following error:

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

If I change the status code in the middleware to anything other than 404 it seems to work as expected.

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

This 404 code was working until I changed the target framework from netcoreapp3.1 to net5.0. What do I need to change in order to successfully return a 404 with JSON from the exception middleware while targeting net5.0?

like image 468
Nick Prince Avatar asked Oct 19 '25 15:10

Nick Prince


1 Answers

The problem seems to step from this update to the ExceptionHandlerMiddleware.

Adding this line fixed the response when the site is running live.

await context.Response.CompleteAsync();

However this line did not fix my test using TestServer, because TestServer does not yet implement CompleteAsync.

like image 70
Nick Prince Avatar answered Oct 22 '25 03:10

Nick Prince