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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With