Take advantage of the extension methods of the IEndpointConventionBuilder interface to implement lightweight services sans template or controller in ASP.NET Core 6. Credit: Jasmina007 / Getty When working in web applications in ASP.NET Core, you might often want to build services that are lightweight — i.e., services that don’t have a template or controller class — for lower resource consumption and improved performance. You can create these lightweight services or APIs in the Startup or the Program class. This article talks about how you can build such lightweight services in ASP.NET Core 6. To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here. Create an ASP.NET Core Web API project in Visual Studio 2022 First off, let’s create an ASP.NET Core project in Visual Studio 2022. Following these steps will create a new ASP.NET Core Web API 6 project in Visual Studio 2022: 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 6.0 (Preview) as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default). Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be using any of those features here. Click Create. We’ll use this new ASP.NET Core 6 Web API project to illustrate working with lightweight services in the subsequent sections of this article. Get started on a lightweight service in ASP.NET Core As we’ll be building lightweight services that don’t require a controller, you should now delete the Controllers solution folder and any model classes that are created by default. Next, open the launchSettings.json file under the Properties solution folder and remove or comment out the launchUrl key-value pair as shown in the code snippet given below. The launchUrl refers to the host of your application. When the application is started, the URL specified in launchURL is used to start the application. If the URL is wrong or does not exist, the application will throw an error at startup. By removing launchUrl or commenting it out, we ensure that the application doesn’t use the default launchUrl to launch the application and thus we avoid any errors. Once the launchUrl is removed, the application will fall back to port 5000. "profiles": { "Light_Weight_Services": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, //"launchUrl": "", "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, //"launchUrl": "", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } Use IEndpointConventionBuilder extension methods in ASP.NET Core We’ll now take advantage of some of the extension methods of the IEndpointConventionBuilder interface to map requests. Here is the list of these extension methods: MapGet MapPost MapDelete MapPut MapRazorPages MapControllers MapHub MapGrpcServices The MapGet, MapPost, MapDelete, and MapPut methods are used to connect the request delegate to the routing system. MapRazorPages is used for RazorPages, MapControllers for Controllers, MapHub for SignalR, and MapGrpcService for gRPC. The following code snippet illustrates how you can use MapGet to create an HTTP Get endpoint. endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); Now create a new C# file named Author and enter the following code: public class Author { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } Create a read-only list of Author and populate it with some data as shown in the code snippet given below. private readonly List<Author> _authors; public Startup(IConfiguration configuration) { _authors = new List<Author> { new Author { Id = 1, FirstName = "Joydip", LastName = "Kanjilal" }, new Author { Id = 2, FirstName = "Steve", LastName = "Smith" }, new Author { Id = 3, FirstName = "Julie", LastName = "Lerman" } }; Configuration = configuration; } You can use the following code to create another endpoint and return the list of Author in JSON format. endpoints.MapGet("/authors", async context => { var authors = _authors == null ? new List<Author>() : _authors; var response = JsonSerializer.Serialize(authors); await context.Response.WriteAsync(response); }); Retrieve a record using lightweight services in ASP.NET Core To retrieve a particular record based on the Id, you can write the following code: endpoints.MapGet("/authors/{id:int}", async context => { var id = int.Parse((string)context.Request.RouteValues["id"]); var author = _authors.Find(x=> x.Id == id); var response = JsonSerializer.Serialize(author); await context.Response.WriteAsync(response); }); Create a record using lightweight services in ASP.NET Core To add data using an HTTP Post endpoint, you can take advantage of the MapPost extension method as shown below. endpoints.MapPost("/", async context => { var author = await context.Request.ReadFromJsonAsync<Author>(); _authors.Add(author); var response = JsonSerializer.Serialize(author); await context.Response.WriteAsync(response); }); Delete a record using lightweight services in ASP.NET Core To delete data, you can take advantage of the MapDelete extension method as shown below. endpoints.MapDelete("/authors/{id:int}", async context => { var id = int.Parse((string)context.Request.RouteValues["id"]); var author = _authors.Find(x => x.Id == id); _authors.Remove(author); var response = JsonSerializer.Serialize(_authors); await context.Response.WriteAsync(response); }); Configure method for lightweight services in ASP.NET Core Here is the complete source code of the Configure method of the Startup class: public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); endpoints.MapGet("/authors", async context => { var authors = _authors == null ? new List() : _authors; var response = JsonSerializer.Serialize(authors); await context.Response.WriteAsync(response); }); endpoints.MapGet("/authors/{id:int}", async context => { var id = int.Parse((string)context.Request.RouteValues["id"]); var author = _authors.Find(x=> x.Id == id); var response = JsonSerializer.Serialize(author); await context.Response.WriteAsync(response); }); endpoints.MapPost("/", async context => { var author = await context.Request.ReadFromJsonAsync<Author>(); _authors.Add(author); var response = JsonSerializer.Serialize(author); await context.Response.WriteAsync(response); }); endpoints.MapDelete("/authors/{id:int}", async context => { var id = int.Parse((string)context.Request.RouteValues["id"]); var author = _authors.Find(x => x.Id == id); _authors.Remove(author); var response = JsonSerializer.Serialize(_authors); await context.Response.WriteAsync(response); }); }); } Create lightweight services in the Program class in ASP.NET Core There is another way to create lightweight services in ASP.NET 6. When you create a new ASP.NET Core 6 Empty Project, the Startup.cs file will not be created by default. So, you can write your code to create lightweight services in the Program.cs file. Here is an example that illustrates how you can do this: app.MapGet("/", () => "Hello World!"); app.MapDelete("/{id}", (Func<int, bool>)((id) => { //Write your code to delete record here return true; })); app.MapPost("/", (Func<Author, bool>)((author) => { //Write your code to add a new record here return true; })); app.Run(); Lightweight services or APIs don’t have a template and don’t need a controller class to create them in. You can create such services in the Startup or the Program class. If you want to implement authorization in the lightweight services demonstrated in this post, you should take advantage of the RequireAuthorization extension method of the IEndpointConventionBuilder interface. Related content news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks how-to How to use DispatchProxy for AOP in .NET Core Take advantage of the DispatchProxy class in C# to implement aspect-oriented programming by creating proxies that dynamically intercept method calls. By Joydip Kanjilal Nov 14, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks news Microsoft’s .NET 9 arrives, with performance, cloud, and AI boosts Cloud-native apps, AI-enabled apps, ASP.NET Core, Aspire, Blazor, MAUI, C#, and F# all get boosts with the latest major rev of the .NET platform. By Paul Krill Nov 12, 2024 4 mins C# Generative AI Microsoft .NET feature Can Wasm replace containers? WebAssembly revolutionized browser apps, and promises to upend the server stack. How will it impact containers and Kubernetes? Six experts weigh in. By Bill Doerrfeld Nov 11, 2024 12 mins Containers Kubernetes Cloud Native Resources Videos