Developer Exception Page Middleware in ASP.NET Core

Developer Exception Page Middleware in ASP.NET Core Application

In this article, I will discuss how to Handle an Unhandled Exception using the Developer Exception Page Middleware Component in an ASP.NET Core Web Application. Please read our previous article about configuring the Default page in the ASP.NET Core Web Application.

Exception handling is an essential feature of any application. In ASP.NET Core, there are multiple ways to handle exceptions, one of which is using the Developer Exception Page Middleware. This middleware is useful during the development phase for diagnosing and resolving issues efficiently.

What is Developer Exception Page Middleware?

The Developer Exception Page Middleware in an ASP.NET Core application diagnoses issues during the development phase. It provides detailed information about unhandled exceptions, helping developers quickly identify and resolve problems. However, using this middleware only in the development environment is recommended, as exposing detailed error information in a production environment can create a significant security risk.

The Developer Exception Page Middleware captures unhandled exceptions in the pipeline and generates an HTML response containing detailed information, including stack traces, source code snippets, and other relevant data. This information can significantly help in diagnosing the root cause of the issue.

For example, imagine an ASP.NET Core Web API project where an API endpoint throws an unhandled exception. With the Developer Exception Page Middleware enabled, you can see exactly where the exception occurred, inspect the request details, and view the stack trace, making it much easier to diagnose and fix the issue.

How Does It Work?

By default, ASP.NET Core applications automatically include the Developer Exception Page Middleware in the Request Processing Pipeline when running the application in the Development environment. When an unhandled exception occurs, the middleware captures it and generates an HTML error response with detailed information.

Understanding Developer Exception Page Middleware in ASP.NET Core:

Let us understand Developer Exception Page Middleware in ASP.NET Core Applications with a few examples. First, create a new ASP.NET Core Application using the Empty Project template. Then, please modify the Program Class as shown below, where we throw an exception from the MapGet endpoint.

namespace FirstCoreWebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            var app = builder.Build();

            app.MapGet("/", async context =>
            {
                int Number1 = 10, Number2 = 0;
                int Result = Number1 / Number2; //This statement will throw Runtime Exception
                await context.Response.WriteAsync($"Result : {Result}");
            });

            //This will Run the Application
            app.Run();
        }
    }
}

When you run the application, you will get the following output.

How to Handle an Unhandled Exception using Developer Exception Page Middleware Component in ASP.NET Core Web Application

As you can see in the above image, the Developer Exception Page provides information such as the exception message, stack trace, and related HTTP request details, making it easier for developers to debug issues.

Now, if you run the application in an environment other than Development (e.g., Staging or Production), you will not see this detailed information. Instead, the response will simply indicate an internal server error (HTTP 500) without exposing sensitive details.

How to Set the Developer Exception Page Middleware Manually:

It is also possible to manually add the Developer Exception Page Middleware to the request processing pipeline. To do this, you need to include the app.UseDeveloperExceptionPage(); middleware explicitly. For example, modify the Program class as follows:

namespace FirstCoreWebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            var app = builder.Build();

            //Using UseDeveloperExceptionPage Middleware to Show Exception Details
            app.UseDeveloperExceptionPage();

            app.MapGet("/", async context =>
            {
                int Number1 = 10, Number2 = 0;
                int Result = Number1 / Number2; //This statement will throw Runtime Exception
                await context.Response.WriteAsync($"Result : {Result}");
            });

            //This will Run the Application
            app.Run();
        }
    }
}

With the above changes, if you run the application in any environment (Development, Staging, Production), you will get the detailed exception page, as shown in the image below. However, this approach in a production environment is not recommended, as it exposes sensitive application details.

How to Handle an Unhandled Exception using Developer Exception Page Middleware Component in ASP.NET Core Web Application

Understanding the Developer Exception Page Tabs

The Developer Exception Page contains five tabs: Stack, Query, Cookies, Headers, and Routing. Let’s understand these tabs in detail:

  • Stack: The Stack tab displays the stack trace of the exception, including method names, file names, and line numbers. This tab helps identify the exact location where the exception was thrown in the code.
  • Query: The Query tab shows the HTTP request’s query string parameters. This helps understand any data sent as part of the URL that may be relevant to the exception.
  • Cookies: The Cookies tab lists all cookies sent with the HTTP request. It helps verify if relevant cookies are present and correctly formatted.
  • Headers: The Headers tab lists all HTTP headers included in the request and response. This helps to verify the presence and values of headers that might impact application behavior.
  • Routing: The Routing tab provides information about how the request was routed. It helps diagnose routing-related issues, such as incorrect route patterns or endpoint mismatches.
Best Practices to Use Developer Exception Page Middleware

We should never use the Developer Exception Page Middleware in a production environment, as it can expose sensitive information about the application’s structure, configuration, and other internal details. Instead, make sure this middleware is only available in the development environment. To ensure the middleware is used correctly, you can add a condition to check the environment before adding the middleware. For a better understanding, please modify the Program class as follows:

namespace FirstCoreWebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            var app = builder.Build();

            //If the Environment is Development, Please Show the Unhandled Exception Details 
            if (app.Environment.IsDevelopment())
            {
                //Using UseDeveloperExceptionPage Middleware to Show Exception Details
                app.UseDeveloperExceptionPage();
            }

            app.MapGet("/", async context =>
            {
                int Number1 = 10, Number2 = 0;
                int Result = Number1 / Number2; //This statement will throw Runtime Exception
                await context.Response.WriteAsync($"Result : {Result}");
            });

            //This will Start the Application
            app.Run();
        }
    }
}

Note: Starting from .NET 6, it is no longer necessary to explicitly configure the Developer Exception Page Middleware in the Program class for the development environment. By default, the framework will enable the developer exception page when the environment is set to Development.

Why Use Developer Exception Page Middleware?

When developing an ASP.NET Core application, encountering unhandled exceptions is common. The Developer Exception Page Middleware helps by:

  • Identifying Errors Quickly: Provides detailed error messages and stack traces to pinpoint the exact location and cause of the exception.
  • Inspecting Request Details: Allows developers to view request-specific data such as query strings, headers, and cookies.
  • Improving Debugging Efficiency: Facilitates faster resolution of issues by presenting all necessary information in one place.

Security Consideration: While detailed error information is beneficial during development, exposing such details in a production environment can lead to security vulnerabilities. Therefore, it’s essential to restrict the middleware’s usage to the development environment only.

In the next article, I will discuss how to Create, Build, and Run ASP.NET Core Applications using .NET Core CLI (Command Line Interface) Commands. In this article, I explain how to handle an unhandled exception using the Developer Exception Page Middleware Component in an ASP.NET Core Web Application with Examples. I hope you enjoy this article om Developer Exception Page Middleware in ASP.NET Core Web Applications.

3 thoughts on “Developer Exception Page Middleware in ASP.NET Core”

  1. It’s missing parameter in app.UseDeveloperExceptionPage method.

    DeveloperExceptionPageOptions developerExceptionPageOptions = new DeveloperExceptionPageOptions
    {
    SourceCodeLineCount = 5
    };
    app.UseDeveloperExceptionPage(developerExceptionPageOptions);

  2. I am getting error on await in Endpoints middleware after throw new Exception. Error message says “Unreachable code detected” S0162.

    1. That’s because your code will stop executing at the point of throwing the error, therefore the next line will never get hit. It’s nothing to worry about in this example – maybe the author should have stated to comment out that line just for clarity.

Leave a Reply

Your email address will not be published. Required fields are marked *