'Status Code Pages in Web API apps in ASP.NET Core - Yes or No

Can we use status code pages middleware to log 400-599 errors in .NET Core Web API App? In Microsoft docs, the option of UseStatusCodePages is given as a common approach for handling errors in web apps. They have not mentioned it in the doc for handling errors in web API apps. Will there be any issue with using Status Code Pages middleware in web API apps when we deploy the app to the cloud? We want to return a 'Problem' response for all errors 400-599. The reason I asked for StatusCodePages is that there are certain status codes that do not raise exceptions and hence are not caught by the Exception Handler Middleware. E.g. 431 - Request Headers too long. Apparently, Status Code Pages should take care of such status codes' responses.



Solution 1:[1]

You could, and it may work for your use case (e.g. If things are blowing up, the text in the response may not matter to you).

However, the reason they are not mentioned in an API context is that it would be bad form for an API that returns JSON only response to start responding with plain text error pages. It's better if you return a JSON response, something like :

{
   "errorCode" : "500", 
   "errorMessage" : "Something went wrong"
}

Which is what you do see with things like the inbuild model validation.

Solution 2:[2]

You could follow the offcial document:https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?wt.mc_id=docsexp4_personal-blog-marouill&view=aspnetcore-5.0

In startup:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseExceptionHandler("/error-local-development");
            }
            else
            {
                app.UseExceptionHandler("/error");
            }
            app.UseHttpsRedirection();
           
            app.UseAuthentication();
            app.UseRouting();

            app.UseAuthorization();
            

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

ErrorController:

[ApiController]
    public class ErrorController : ControllerBase
    {
        [Route("/error-local-development")]
        public IActionResult ErrorLocalDevelopment(
            [FromServices] IWebHostEnvironment webHostEnvironment)
        {
            if (webHostEnvironment.EnvironmentName != "Development")
            {
                throw new InvalidOperationException(
                    "This shouldn't be invoked in non-development environments.");
            }

            var context = HttpContext.Features.Get<IExceptionHandlerFeature>();

            return Problem(
                detail: context.Error.StackTrace,
                title: context.Error.Message);
        }

        [Route("/error")]
        public IActionResult Error() => Problem();
    }

My test result: enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MindingData
Solution 2 Ruikai Feng