Extending Functionality of Your ASP.NET Core Application

Introduction

Welcome to this lesson on extending the functionality of your ASP.NET Core application! By now, you should be familiar with the basics of ASP.NET Core and have successfully created a simple application that outputs "Hello, World!". In this lesson, we’ll elevate that basic application by understanding its structure, adding services, defining middleware, and creating endpoints. Ultimately, we aim to gain a better grasp of how to expand your ASP.NET Core application.

Simplest Program.cs file structure recap

In the previous lesson, we saw a very simple structure of the Program.cs file that consisted of just four lines of code:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Welcome to CodeSignal Learn!");

app.Run();

In this lesson, we'll explore how we can expand this structure and add more functionality to our application.

Extending the application functionality

You can extend the functionality of your application using several approaches:

  1. Registering Services: Services in ASP.NET Core are modular components that provide specific functionalities to the application. These services are essentially C# classes that are registered using the Services property of the WebApplicationBuilder. For example, you might add the HttpLoggingService, a built-in ASP.NET Core service that logs incoming requests. Once registered, the application becomes "aware" of the service and can instantiate and utilize it as needed. It's important to note that services must be registered before they can be used in middleware.

  2. Adding Middleware: Middleware is a series of components through which each HTTP request and response flows. For example, you can add HttpLogging middleware to log every incoming request. However, since this middleware depends on the HttpLoggingService, you need to register the service first. Middleware components execute in the order they are added.

  3. Mapping Endpoints: You can extend functionality by defining new endpoints. For instance, you might add an endpoint for a Todo app, enabling users to retrieve all Todo items.

Here's a schematic representation of how an extended Program.cs file can look:

var builder = WebApplication.CreateBuilder(args);

// 1. Register services on the builder instance here

var app = builder.Build();

// 2. Add middleware on the app instance here

// 3. Map endpoints on the app instance here

app.Run();

Don't worry if this doesn't make sense right away—we'll walk you through each of these approaches in the following sections.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal