Navigation
Search
|
How to use FastEndpoints in ASP.NET Core
Thursday July 11, 2024. 11:00 AM , from InfoWorld
FastEndpoints is a free and open-source REST API development framework for.NET Core that can be used to build lightweight and fast APIs. In this article, we’ll examine this library and learn how to use it to build lightweight APIs in ASP.NET Core applications.
ASP.NET Core supports two built-in approaches to building APIs, traditional controllers and minimal APIs. Traditional controllers (i.e., MVC and API controllers in ASP.NET Core) are feature-rich, but they require writing a lot of boilerplate code and they don’t match minimal APIs in performance. Minimal APIs are lightweight and fast, but they support only a minimal set of features. A third option is to use a third-party library for building APIs such as FastEndpoints, which combines benefits of both controllers and minimal APIs. While minimal APIs are slightly faster than FastEndpoints, FastEndpoints provides several features that are not supported by minimal APIs including model binding, rate limiting, and caching. Moreover, if you use FastEndpoints in lieu of minimal APIs, you can take advantage of Swagger or OpenAPI to document your APIs. Introducing FastEndpoints An implementation of the REPR (Request-Endpoint-Response) design pattern, FastEndpoints is a developer-friendly, minimalist alternative to minimal APIs and traditional MVC and API controllers. The REPR design pattern simplifies API development by organizing your APIs around endpoints instead of controllers. It provides distinct separation between the input request, the logic at the endpoint, and the output response. In the sections that follow, we’ll examine how we can use FastEndpoints to build fast and lean APIs in ASP.NET Core. Our implementation will include an endpoint class, a request DTO (Data Transfer Object) class, and a response DTO class. Create an ASP.NET Core Web API project in Visual Studio 2022 To create an ASP.NET Core Web API project in Visual Studio 2022, follow the steps outlined below. Launch the Visual Studio 2022 IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Next. In the “Additional Information” window shown next, select “.NET 8.0 (Long Term Support)” as the framework version and uncheck the check box that says “Use controllers,” as we’ll be using minimal APIs in this project. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable OpenAPI Support,” “Configure for HTTPS,” and “Enable Docker” remain unchecked. We won’t be using any of those features here. Click Create. We’ll use this ASP.NET Core Web API minimal API project to work with the code examples given in the sections below. Install the FastEndpoints NuGet package To work with FastEndpoints library, we’ll need to install the FastEndpoints NuGet package in the project. To do this, select the project in the Solution Explorer window, then right-click and select “Manage NuGet Packages.” In the NuGet Package Manager window, search for the FastEndpoints package and install it. Alternatively, you can install the packages via the NuGet Package Manager console by entering the command shown below. PM> Install-Package FastEndpoints Register the FastEndpoints library To add FastEndpoint services to the ASP.NET Core request processing pipeline, enter the following line of code in the Program.cs file. builder.Services.AddFastEndpoints(); Note that at runtime, the FastEndpoints library excludes endpoints that are located in any of the assembly names that are part of the exclusion list. You can take a look at how that has been implemented here. If your endpoint is located in any of those assembly names, the FastEndpoints library will throw an exception at runtime during its registration process. To avoid this exception, rename your project to a name that is not on the exclusion list or specify an assembly name manually as shown in the following code snippet. builder.Services.AddFastEndpoints( o => o.Assemblies = new[] { typeof(FastEndpoints_Demo.MyFirstRequest).Assembly, typeof(FastEndpoints_Demo.MyFirstResponse).Assembly }); Next we’ll create our first endpoint using the FastEndpoints library. This endpoint will handle a HTTP POST request and send the response back to the client. Create a request class To create a request DTO, create a new C# class named MyFirstRequest and replace the generated code with the following code snippet. namespace FastEndpoints_Demo{ public class MyFirstRequest { public string FirstName { get; set; } public string LastName { get; set; } }} Create a response class To create a response DTO, create a new C# class named MyFirstResponse and replace the generated code with the following code. namespace FastEndpoints_Demo{ public class MyFirstResponse { public string Message { get; set; } }} Create an endpoint class An endpoint class can be created by extending the Endpoint base class. Your custom endpoint class should use the request and response DTOs to store data. Let’s now create a new C# class named MyFirstEndpoint and give it the following code. using FastEndpoints;namespace FastEndpoints_Demo.Endpoints{ public class MyFirstEndpoint: Endpoint { public override void Configure() { Post('/api/author/create'); AllowAnonymous(); } public override async Task HandleAsync(MyFirstRequest request, CancellationToken token) { await SendAsync(new() { Message = $'The author name is: {request.FirstName} {request.LastName}' }); } }} As you can see in the preceding code listing, the custom endpoint class should override the Configure and HandleAsync methods. Configure is used to configure how your custom endpoint should listen to incoming requests. HandleAsync contains the necessary logic for processing the request and sending back the response. Complete Program.cs file The following is the complete source code of the Program.cs file for your reference. using FastEndpoints;var builder = WebApplication.CreateBuilder();builder.Services.AddFastEndpoints( o => o.Assemblies = new[] { typeof(FastEndpoints_Demo.MyFirstRequest).Assembly, typeof(FastEndpoints_Demo.MyFirstResponse).Assembly });var app = builder.Build();app.UseFastEndpoints();app.Run(); Execute the application Finally, run the application and browse the endpoint using Postman with the following request body. { 'FirstName': 'Joydip', 'LastName': 'Kanjilal'} Figure 1 shows the output you should see upon invoking the endpoint. Figure 1. FastEndpoints in action. IDG FastEndpoints is a free third-party alternative to ASP.NET Core’s built-in legacy controllers and minimal APIs. FastEndpoints combines performance on a par with minimal APIs and a structured approach to handling HTTP requests and responses. I’ll demonstrate how we can implement security, versioning, validation, dependency injection, caching, and rate limiting with FastEndpoints in future posts here.
https://www.infoworld.com/article/2515537/how-to-use-fastendpoints-in-asp-net-core.html
Related News |
25 sources
Current Date
Nov, Thu 21 - 15:24 CET
|