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 discussing how to configure the default page in the ASP.NET Core Web Application.

Exception Handling is one of the key features of any application. We can handle the exception in many different ways. However, in this article, I will discuss how we can use the Developer Exception Page Middleware Component to handle the unhandled exception in the ASP.NET Core Web Application. As part of this article, we will discuss the following concepts.

  1. What is Developer Exception Page Middleware?
  2. How do you use Developer Exception Page Middleware in ASP.NET Core Application?
  3. How do you customize the UseDeveloperExceptionPage Middleware in ASP.NET Core?
  4. Where do we need to configure the UseDeveloperExceptionPage Middleware?
Developer Exception Page Middleware in ASP.NET Core

The Developer Exception Page Middleware is designed to catch unhandled exceptions that occur during the request pipeline processing in an ASP.NET Core application. When an exception is thrown, this middleware displays a detailed error page, showing a stack trace and other debugging information. It’s typically used only in the development environment, as exposing detailed error information in production can be a security risk. 

Understanding Developer Exception Page Middleware in ASP.NET Core:

First, create an ASP.NET Core Application with the Empty Project template. To create a new Empty ASP.NET Core Web Application, open Visual Studio 2022 and click the Create a new project tab, as shown in the image below.

Understanding Program.cs Class File in ASP.NET Core

Once you click on the Create a new project tab, it will open the Create a new project window. You need to select the ASP.NET Core Empty project template from this window and click the Next button, as shown in the image below.

What is a Host in ASP.NET Core?

Once you click on the Next button, it will open the Configure Your New Project window. Here, you must provide the necessary information to create a new project. First, give an appropriate name for your project (FirstCoreWebApplication), set the location where you want to create this project, and the solution name for the ASP.NET Core Web application. And finally, click on the Create button, as shown in the image below.

What is Program Class?

Once you click on the Next button, the Additional Information window will open. Here, you need to select .NET 6.0 as the Framework. You also need to check the Configure for HTTPS and do not use top-level statements check boxes, and finally, click the Create button, as shown in the image below.

ASP.NET Core Main Method in .NET 6

That’s it. Once you click on the Create Button, the project will be created using the Empty template. By default, the ASP.NET Core Web Application (.NET 6) returns the Developer Exception Page in the Development Environment if the application does not handle the exception. Let us understand this with an example. Please modify the Main() method of the Program Class as shown below, where we throw an exception.

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, we are getting the details of the exceptions on the page. This is because the .NET Core Framework automatically enables the developer exception page for the Development environment. If you want, then you can also add the Developer Exception Page Middleware component within the Main method of 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();
        }
    }
}

With this change, run the application, and you will also get the same exception page as shown in the below image.

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 contains five tabs: Stack, Queue, Cookies, Headers, and Routing.

  1. Stack: The Stack tab gives the information of stack trace, which indicates where exactly the exception occurred, the file name, and the line number that caused the exception.
  2. Query: The request’s query string that caused the exception is shown. This is useful for understanding the parameters that were passed to the server using query strings.
  3. Cookies: The Developer Exception Page shows all cookies associated with the request. This is useful for debugging session management, authentication, or user preferences issues.
  4. Header: HTTP headers contain information about the request and the client. They include data like content type, response status code, client information, and more. The Developer Exception Page lists all the request headers, which can be useful for troubleshooting issues related to caching, content negotiation, authentication, etc.
  5. Routing: It refers to how ASP.NET Core maps incoming requests to route handlers. This information is useful for debugging issues related to route configuration, URL patterns, and route constraints.

Note: Please Enable the Developer Exception Page Middleware only when the application runs in the Development environment. You don’t want to share detailed exception information when the application runs in production.

How do you customize the UseDeveloperExceptionPage Middleware in ASP.NET Core?

Customizing the Developer Exception Page Middleware in ASP.NET Core allows you to modify the behavior and appearance of the displayed error page during development. This can be useful for adding additional debugging information, changing the layout, or styling. Whenever you want to customize a middleware component in ASP.NET Core, you need to use the respective Options object. For example

  1. UseDeveloperExceptionPage => To customize UseDeveloperExceptionPage middleware, use the DeveloperExceptionPageOptions object.
  2. UseDefaultFiles => To customize UseDefaultFiles middleware, use the DefaultFilesOptions object
  3. UseStaticFiles => To customize UseStaticFiles middleware, use the StaticFileOptions object
  4. UseFileServer => To customize UseFileServer middleware, use the FileServerOptions object

As we customize the UseDeveloperExceptionPage() middleware component, we must use the DeveloperExceptionPageOptions object. So, modify the Main method of the Program class as shown below.

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())
            {
                //Create an Instance of DeveloperExceptionPageOptions to Customize
                //UseDeveloperExceptionPage Middleware Component
                DeveloperExceptionPageOptions developerExceptionPageOptions = new DeveloperExceptionPageOptions
                {
                    SourceCodeLineCount = 5
                };

                //Passing DeveloperExceptionPageOptions Instance to UseDeveloperExceptionPage Middleware Component
                app.UseDeveloperExceptionPage(developerExceptionPageOptions);
            }

            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();
        }
    }
}

As you can see in the above code, we are using one property called SourceCodeLineCount. The SourceCodeLineCount property of the DeveloperExceptionPageOptions class specifies the number of lines of code to include before and after the line of code that caused the exception.

Now, if you run the application with the above changes in place, you will get the following error. Please have a look at the error line number 28. Also, please look at the number of lines before and after the error line.

How to Customize the UseDeveloperExceptionPage Middleware in ASP.NET Core?

Note: From.NET6, there is no need to configure the developer exception page middleware explicitly. By default, the Framework will load the developer exception page if the environment is Development.

Best Practices to Use Developer Exception Page Middleware
  • Not for Production: Never use the Developer Exception Page Middleware in a production environment. It can expose sensitive information about the application structure, database, and other internals.
  • Combine with Logging: While this middleware is helpful for immediate debugging, it’s also important to implement robust logging for exceptions to track and analyze errors over time.

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 this article will help you understand the Developer Exception Page Middleware in ASP.NET Core Web Applications.

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

  1. blank

    It’s missing parameter in app.UseDeveloperExceptionPage method.

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

  2. blank

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

    1. blank

      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 *