How to use the Developer Exception Page in ASP.NET Core MVC


The Developer Exception Page in ASP.NET Core provides detailed information about exceptions. Because developers need detailed information about exceptions, and end users don’t, the ASP.NET Core templates enable the Developer Exception Page only when an application is running in the Development environment.

This article talks about the Developer Exception Page Middleware in ASP.NET Core MVC and how we can handle exceptions in both development and production environments in ASP.NET Core MVC applications.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create an ASP.NET Core MVC project in Visual Studio 2019

First off, let’s create an ASP.NET Core project in Visual Studio 2019. Following these steps will create a new ASP.NET Core MVC 5 project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, select .NET 5.0 as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we won’t be using any of those features here.
  10. Click Create.

A new ASP.NET Core MVC project will be created. We’ll use this project to work with the Developer Exception Page middleware in the subsequent sections of this article.

Next follow the steps outlined below to create additional controller(s) in your project:

  1. Right-click on the Controllers solution folder.
  2. Select Add -> Controller.
  3. In the “Add New Scaffolded Item” dialog, select API as the template (by default MVC would be selected).
  4. Select the item “API Controller with read/write actions.”
  5. Click Add.
  6. In the “Add New Item” dialog shown next, specify a name for your new controller.
  7. Click Add.

Handling exceptions in ASP.NET Core MVC

Consider the following piece of code that throws an exception in the Configure method of the startup class:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
      app.UseStaticFiles();
      app.UseRouting();
      app.UseAuthorization();
      app.UseEndpoints(endpoints = >{
            endpoints.MapControllerRoute(
            name: "default", pattern:
"{controller=Home}/{action=Index}/{id?}");
      });
      throw new Exception("An error occurred while processing the request");
}

When you run the above application, an exception will be thrown with the error messages shown in Figure 1 below.

developer exception page 01 IDG

Figure 1.

As you can see in Figure 1, the error messages displayed here are neither detailed nor developer-friendly. A better option is to use the Developer Exception Page.

Exception handling in the Development environment

The Developer Exception Page middleware provides developer-friendly error messages when an exception is thrown in the application. This information helps you to trace the errors that occur when the application is running in the Development environment.

The Developer Exception Page groups this detailed information into five tabbed sections — Stack, Query, Cookies, Headers, and Routing — as shown in Figure 2 below.

developer exception page 02 IDG

Figure 2.

When you create a new ASP.NET Core MVC project in Visual Studio, the ASP.NET Core template generates the following code in the Configure method of the Startup class.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
      if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
      }
      else {
            app.UseExceptionHandler("/Home/Error");
      }
      app.UseStaticFiles();
      app.UseRouting();
      app.UseAuthorization();
      app.UseEndpoints(endpoints = >{
            endpoints.MapControllerRoute(
            name: "default", pattern:
"{controller=Home}/{action=Index}/{id?}");
      });
}

As the preceding code indicates, the Developer Exception Page will be enabled only when the application is running in the Development environment. The Developer Exception Page is not enabled when the application is running in the Production environment. Naturally, the purpose is to avoid displaying exception messages publicly.

Note that the UseDeveloperExceptionPage extension method is called at the beginning of the pipeline, before any other middleware is called. This is done to ensure that exceptions in the following middleware will be caught.

Exception handling in the Production environment

For handling exceptions in the Production environment, you should take advantage of the UseExceptionHandler extension method. The following code listing illustrates how the UseExceptionHandler extension method can be called in the Configure method of the Startup class.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
      if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
      }
      else {
            app.UseExceptionHandler("/Home/Error");
      }
      app.UseStaticFiles();
      app.UseRouting();
      app.UseAuthorization();
      app.UseEndpoints(endpoints = >{
            endpoints.MapControllerRoute(
            name: "default", pattern:
            "{controller=Home}/{action=Index}/{id?}");
      });
}

The UseExceptionHandler extension method can be used to configure custom error handling routes. Refer to the following code snippet.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
      if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage(developerExceptionPageOptions);
      }
      else {
            app.UseExceptionHandler("/Home/Error");
      }
      //Other code removed for brevity
}

When an error occurs in the ASP.NET Core MVC application, the control will be redirected to /home/error.

Note you could use a lambda expression in the UseExceptionHandler extension method in lieu of using a custom exception handler page. The following code snippet illustrates how this can be achieved.

app.UseExceptionHandler(errorApp = >{
      errorApp.Run(async context = >{
            context.Response.StatusCode = (int)
HttpStatusCode.InternalServerError;
            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync("<html
lang="en"><body>rn");
            await context.Response.WriteAsync("An error occurred...<br><br>rn");
            await context.Response.WriteAsync("</body></html>rn");
            await context.Response.WriteAsync(new string(' ', 512));
      });
});

The Developer Exception Page is available by adding the Developer Exception Page middleware to the ASP.NET Core MVC request processing pipeline. The default template in ASP.NET Core MVC enables this middleware for the Development environment only. For Production, you can take advantage of the UseExceptionHandler extension method to configure custom error handling.

Copyright © 2021 IDG Communications, Inc.



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here