Search code examples
c#exceptionasp.net-coreasp.net-core-webapiasp.net-core-2.2

How to use "problem detail" responses for unhandled exceptions?


As documented, ProblemDetails (based on the RFC 7807 specification) is the standard response for client error codes in ASP.NET Core 2.2. This works fine when I return things like NotFound() in my API controller action methods.

But how do I configure my Web API project to also use ProblemDetails for unhandled exceptions ("500 Internal Server Error" responses)? By default such unhandled exceptions either return a HTML body (when UseDeveloperExceptionPage() or UseExceptionHandler(somePath) was called) or no body (if neither method was called).

My preferred solution would always return a ProblemDetails object when an exception happens in API controllers, but still return HTML pages for exceptions on other (view related) controllers. In development mode the ProblemDetails object should have full exception details, in production only very limited details. Is this possible?


Solution

  • It seems that ProblemDetails does not support for 404 and 500 exception. A workaround is to install the Hellang.Middleware.ProblemDetails package:

    Install-Package Hellang.Middleware.ProblemDetails
    

    And then configure in startup.cs, set IncludeExceptionDetails to true under development environment only.

    public class Startup
    {
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            CurrentEnvironment = env;
        }
    
        public IConfiguration Configuration { get; }
        public IHostingEnvironment CurrentEnvironment { get; }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddProblemDetails(setup=> {
              
                setup.IncludeExceptionDetails = _ => CurrentEnvironment.IsDevelopment();
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
    
        public void Configure(IApplicationBuilder app)
        {           
            app.UseProblemDetails();           
            //...
        }
    }
    

    Refer to here.