How to use the ProblemDetails middleware in ASP.NET Core

0
19


For an API to be maintainable and usable there should be consistency in the way responses are sent to the clients. This article talks about , open source ASP.NET Core middleware from Kristian Hellang that can be used to generate detailed results for the exceptions that occur in your application.

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 . 

[  ]

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. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” 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 Create.
  8. In the “Create a New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and ASP.NET Core 3.1 (or later) from the drop-down list at the top.
  9. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application. 
  10. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  11. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either.
  12. Click Create.

This will create a new ASP.NET Core MVC project in Visual Studio 2019. Next, create a new ApiController class named ValuesController. We’ll use this class and the project in the sections that follow.

What is ProblemDetails? Why do we need it?

One of the goals of REST APIs is consistency, i.e., being able to emit responses in a consistent manner. When working with these APIs you might often need to define response formats for the errors that occur in your application. While you could use HTTP Status Codes for this purpose, you will often want to communicate more detailed information to the clients than they provide.

For example, consider the failure of a payment in a shopping cart application. The payment might have failed for any number of reasons, such as insufficient bank funds, incorrect credit card information, wrong one-time password code, or a failure in the transaction processing system. Hence, it is imperative that there is a standard way in which these error messages can be sent to the client.

, that defines a format that can be used to send out machine-readable details about the errors that occur in an application. You can take advantage of this format in the ProblemDetails middleware to define errors and error messages in HTTP API responses. Plus, all of your exceptions can be handled in one place: You can always return an instance of ProblemDetails to the consuming client irrespective of the type of error that has occurred.

By using ProblemDetails to emit error response messages, you enable the consumers of the API to react to the errors more effectively. This makes your API consistent and reliable. 

IDG

Figure 1

You can also create an instance of the Microsoft.AspNetCore.Mvc.ProblemDetails class and pass it back to the client as shown in the code listing given below.

try
{
    i = 10 / x;
}
catch (Exception ex)
{
   var problemDetails = new Microsoft.AspNetCore.Mvc.ProblemDetails
   {
       Status = StatusCodes.Status403Forbidden,
       Type = "https://example.com/probs/out-of-credit",
       Title = "Division by zero...",
       Detail = ex.StackTrace,
       Instance = HttpContext.Request.Path
   };
   return BadRequest(problemDetails);
}
IDG

Figure 2

Customize the behavior of the ProblemDetails middleware in ASP.NET Core

You can customize the behavior of the ProblemDetails middleware by using ProblemDetailsOptions in the ConfigureServices method as shown below. 

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddProblemDetails(opts => {
            // Specify your configuration details here
            });
        }

Here is another example. The following configuration will make sure that exception details are included only if you’re in the development environment.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddProblemDetails(opts => {
                opts.IncludeExceptionDetails = (context, ex) =>
                {
              var environment =
   context.RequestServices.GetRequiredService
  <IHostEnvironment>();
                    return environment.IsDevelopment();
                };
            });
        }

ProblemDetails is a machine-readable format that is used to standardize error messages in API controllers and represent HTTP API responses based on the . The Microsoft.AspNetCore.Mvc namespace contains a ProblemDetails class you can use for sending out a machine-readable error response. Kristian Hellang’s ProblemDetails middleware makes this easy. 

How to do more in ASP.NET Core:

Copyright © 2020 IDG Communications, Inc.

LEAVE A REPLY