Joydip Kanjilal
Contributor

How to build lightweight services in ASP.NET Core 6

how-to
Aug 11, 20217 mins
C#Development Libraries and FrameworksMicrosoft .NET

Take advantage of the extension methods of the IEndpointConventionBuilder interface to implement lightweight services sans template or controller in ASP.NET Core 6.

dandelion fragile fall digital transformation fly growth jasmina007 getty
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:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” 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 Next.
  8. 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).
  9. 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.
  10. 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.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author