• Sat. Oct 26th, 2024

How to build lightweight services in ASP.NET Core 6

Byadmin

Aug 11, 2021


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 2022First 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 CoreAs 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 mentioned there as shown in the code snippet given below. “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 CoreWe’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(“https://www.infoworld.com/”, 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 CoreTo 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 CoreTo add data using an HTTP Post endpoint, you can take advantage of the MapPost extension method as shown below.endpoints.MapPost(“https://www.infoworld.com/”, 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 CoreTo 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 CoreHere 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(“https://www.infoworld.com/”, async context =>{   await context.Response.WriteAsync(“Hello World!”);});endpoints.MapGet(“/authors”, async context =>{    var authors = _authors == null ? new List<Author>() : _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(“https://www.infoworld.com/”, 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 CoreThere 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(“https://www.infoworld.com/”, () => “Hello World!”);app.MapDelete(“/{id}”, (Func<int, bool>)((id) => {    //Write your code to delete record here    return true;}));    app.MapPost(“https://www.infoworld.com/”, (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.

Copyright © 2021 IDG Communications, Inc.



Source link