In ASP.NET Core 7, very little APIs provide a light-weight method to create web APIs with less boilerplate code. Nevertheless, errors can still happen and you need to be able to handle them elegantly.This post goes over how we can deal with mistakes gracefully in minimal API apps in ASP.NET Core 7. To use the code examples provided in this short article, you must have Visual Studio 2022 installed in your system. If you don’t currently have a copy, you can download Visual Studio 2022 here.
Produce an ASP.NET Core 7 very little Web API project in Visual Studio 2022
To begin with, let’s develop an ASP.NET Core 7 task in Visual Studio 2022. Follow these steps:
- Release the Visual Studio 2022 IDE.
- Click on “Produce brand-new project.”
- In the “Develop new project” window, choose “ASP.NET Core Web API” from the list of templates displayed.
- Click Next.
- In the “Configure your brand-new task” window, define the name and location for the new task.
- Optionally examine the “Place solution and job in the very same directory site” check box, depending on your choices.
- Click Next.
- In the “Extra Information” window shown next, pick “NET 7.0 (Present)” as the structure and uncheck the check box that says “Usage controllers …” Leave the “Authentication Type” as “None” (default).
- Guarantee that the check boxes “Enable OpenAPI Support,” “Enable Docker”, “Configure for HTTPS,” and “Enable Open API Support” are unattended as we won’t be utilizing any of those features here.
- Click Produce.
We’ll use this ASP.NET Core 7 Web API task to produce a minimal API and implement error handling in the areas below.Handling mistakes
in very little API applications
Change the default produced source code of the Program.cs file in the task we produced with the following code snippet.var builder=
WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet(“/”, () => “Hi World!”); app.Map(“/ mistake”, () => ); app.Run();
When you run the application, the “Hello World” text will be shown in your web internet browser. If you browse to the/ error endpoint, a run time error will happen, and the execution of the application will stop, as shown in Figure 1.
IDG Figure 1. A deadly exception in our very little API application. There are two integrated mechanisms for handling errors in minimal API applications, the Designer Exception Page middleware and the Exception Handler middleware. Let’s analyze each in turn.
Utilizing the Designer Exception Page middleware
To assist designers identify and fix mistakes throughout advancement, you can use the Designer Exception Page middleware. The Designer Exception Page middleware displays detailed error info in the web browser when an exception happens.
Here is an example of how to use the Designer Exception Page middleware in a very little API.var home builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer();// builder.Services.AddSwaggerGen(); var app = builder.Build(); if (app.Environment.IsDevelopment()) app.MapGet(“/”, () => “Hi, world!”); app.Run();
In this example, the UseDeveloperExceptionPage technique is utilized to add the middleware to the pipeline. The middleware is enabled just when the application is running in the Development environment, which is identified by the app.Environment.IsDevelopment() method.If an exception
takes place within the pipeline, the Designer Exception Page middleware catches it and displays a detailed error page in the internet browser. The mistake page consists of information about the exception, consisting of the stack trace, demand information, and environment variables as displayed in Figure 2.
IDG Figure 2. The Developer Exception Page middleware in action. By utilizing the Designer Exception Page middleware, developers can quickly identify and repair errors throughout advancement.
Using the Exception Handler middleware
The Exception Handler middleware catches unhandled exceptions and returns an error action. Normally, you must utilize this middleware in a non-development environment. Here is an example of how to utilize the Exception Handler middleware in a very little API.var contractor = WebApplication.CreateBuilder(args); var app = builder.Build(); app.UseExceptionHandler(exceptionHandlerApp => exceptionHandlerApp.Run(async context => await Results.Problem(). ExecuteAsync(context))); app.Map(“/ mistake”, () => toss brand-new InvalidOperationException(“An Error Happened …”); ); app.MapGet(“/”, () => “Hello, world!”); app.Run();
In this example, the UseExceptionHandler technique is used to configure this middleware. The parameter “/ mistake” specifies the endpoint to which the middleware will reroute in case of an exception.If an unhandled exception occurs within the pipeline, the Exception Managing middleware catches it and reroutes the request to the defined endpoint. Subsequently the error will be dealt with and a proper mistake message returned.By using the Exception Dealing with middleware, you can quickly deal with exceptions that happen within very little APIs in ASP.NET Core 7. This can assist to improve the reliability and usability of your API. Using ProblemDetails for reaction format The ProblemDetails class is a way to consist of information of error
information to avoid producing customized mistake response formats in ASP.NET Core. The AddProblemDetails extension method referring to the IServiceCollection user interface can be used to sign up a default application of the IProblemDetailsService.The following middleware in ASP.NET Core produces ProblemDetails HTTP actions when you telephone to the AddProblemDetailsMiddleware technique in your application. ExceptionHandlerMiddleware: This middleware is utilized to generate a ProblemDetails action if no custom-made handler is
- offered. DeveloperExceptionPageMiddleware: The DeveloperExceptionPageMiddleware develops a ProblemDetails action if the Accept HTTP
- header does not consist of text/html. StatusCodePagesMiddleware: By default, StatusCodePagesMiddleware produces ProblemDetails reactions. The following code listing demonstrates how you can use ProblemDetails in your very little APIs.var contractor=WebApplication.CreateBuilder(args ); builder.Services.AddProblemDetails(); var app=
builder.Build (); app.UseExceptionHandler (); app.UseStatusCodePages (); app.Map(“/ authors/ “,(int id)=> id ); app.Run(); public record Author(int Id); In this example, the/ mistake endpoint extracts the exception details from the HttpContext and develops a ProblemDetails things with the mistake information. It then sets the response status code and content type, and returns the ProblemDetails object as a JSON response.Using Status Code Pages middleware to produce a reaction body When an ASP.NET Core app encounters HTTP mistake codes such as “404-Not Found
,”it does not supply a status code page by default. Whenever a response body is not attended to an HTTP 400-599 mistake status code, the app returns the status code and an empty reaction body.You can conjure up the UseStatusCodePages technique in the Program.cs file of your application to enable text-only handlers for common mistake status codes. You can use the StatusCodePagesMiddleware class in ASP.NET Core to create the response as shown in the code bit provided below.var contractor =WebApplication.CreateBuilder (args ); var app=builder.Build (); app.UseStatusCodePages(async statusCodeContext= > await Results.Problem (statusCode: statusCodeContext.HttpContext.Response.StatusCode). ExecuteAsync(statusCodeContext.HttpContext) ); app.Map(“/ authors/ “,(int id)= > id