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, basic ASP.NET templates enable the developer exception page only when an application is running in the development environment.

This article talks about 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 in this article, you must have Visual Studio 2019 installed on 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, let’s create an ASP.NET Core project in Visual Studio 2019. By following these steps a new ASP.NET Core MVC 5 project will be created in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click 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 of the new project.
  6. Optionally, select the “Place the solution and project in the same directory” check box, based on your preference.
  7. Click {Next.
  8. In the Additional Information window shown next, select .NET 5.0 as the target framework from the dropdown menu at the top. Leave Authentication Type as None (default).
  9. Make sure the “Enable Docker”, “Configure for HTTPS” and “Enable Razor Runtime Aggregation” checkboxes are unchecked as we will not be using any of these features here.
  10. Click Create.

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

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

  1. Right-click on the Console Solutions folder.
  2. Select Add -> Controller.
  3. In the Add New Scaffolding Element dialog, select API as template (MVC will be selected by default).
  4. Select the item “API Controller with Read / Write Actions”.
  5. Click Add.
  6. In the Add New Item dialog displayed next, specify a name for the new console.
  7. Click Add.

Exception Handling 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 the above application is run, 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 shown here are neither detailed nor developer friendly. The best option is to use the developer exception page.

Handling exceptions in the development environment

Developer Exception Page middleware provides convenient error messages to developers when an exception is thrown in the application. This information helps you track 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 Startup class’s Configuration method.

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 previous code indicates, the developer exception page will only be enabled when the application is running in the development environment. The developer exception page is not enabled when the application is running in a production environment. Of course, the purpose is to avoid public display of exception messages.

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 will be caught in the following middleware.

Exception handling in a production environment

To handle exceptions in a production environment, you should make use of the UseExceptionHandler extension method. The following code list shows how the UseExceptionHandler extension method can be called in the startup class’s configuration method.

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 paths. 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 ASP.NET Core MVC application error occurs, the control will be redirected to /home/error.

Note that you can use a lambda expression in the UseExceptionHandler extension method instead of using a custom exception handler page. The following code snippet shows 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 allows these middleware only for the development environment. 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

Your email address will not be published.