How does setting the ExceptionHandlerOptions.AllowStatusCode404Response property work at the version and server level?

Diaz, Francisca 0 Reputation points
2023-08-09T15:48:19.6233333+00:00

I have a nuget which contains a custom exception handler in .NET 7 and then I consume it in an API created in .NET 6, but it presents problems regarding StatusCode 404, in Development it correctly responds to this error, but in the cloud it responds to StatusCode 500 in this case with the following description:

System.InvalidOperationException: The exception handler configured on ExceptionHandlerOptions produced a 404 status response. This InvalidOperationException containing the original exception was thrown since this is often due to a misconfigured ExceptionHandlingPath. If the exception handler is expected to return 404 status responses then set AllowStatusCode404Response to true.

Previously I had one in .NET 6 which did not prompt me for this configuration that apparently exists since .NET 5.

What changes towards .NET 7 have made this setting mandatory? Why does Development return error 404 correctly and Cloud returns 500 without this configuration?

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-08-10T08:21:00.0566667+00:00

    Hi @Diaz, Francisca

    ASP.NET Core 5 introduced breaking-change in handling the response status code NotFound 404. Use ExceptionHandlerOptions.AllowStatusCode404Response property.

    To set the AllowStatusCode404Response property, you can use the following code:

        app.UseExceptionHandler(new ExceptionHandlerOptions()
        {
            AllowStatusCode404Response = true,
            ExceptionHandlingPath = "/error"
        });
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.