Understanding and Implementing Middleware in ASP.NET Core

anishjoshi1999

Anish Joshi

Posted on July 3, 2023

Understanding and Implementing Middleware in ASP.NET Core

Introduction:

Middleware is a crucial component in ASP.NET Core that plays a vital role in handling requests and responses in the application pipeline. In this article, we will explore the definition of middleware, its purpose, and how it can be created and added to the application pipeline. We will also demonstrate the basic usage of middleware in an ASP.NET Core project.

What is Middleware?

Middleware can be understood as a set of methods that execute in a sequential order whenever a request is received. Each method in this sequence is called middleware. When a request is received, the first middleware executes, followed by the second, third, and so on. Once all the middlewares have completed their execution, the response is sent back to the browser. Middlewares are chained together and execute in the same sequence they are added to the pipeline.

Creating and Adding Middleware:

To add middleware in an ASP.NET Core application, you start with an empty application request pipeline and then add the middleware one by one. Each middleware performs a specific operation, following the principle of the single responsibility. For example, a middleware could handle HTTPS redirection, enable static files redirection, or provide authentication and authorization.

Middleware can be created in two ways: as a single anonymous method or lambda expression, or as a separate middleware class. For simple operations, a lambda expression or anonymous method can be used directly. However, for more complex functionality, it's better to organize the code into a separate middleware class. Regardless of the approach, the middleware should be able to forward the request to the subsequent middleware in the pipeline, except for terminal or short-circuiting middleware.

Basic Usage of Middleware in ASP.NET Core:

using Middleware;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
Enter fullscreen mode Exit fullscreen mode

In this part, we first import the Middleware namespace. Then, we create a new instance of WebApplicationBuilder by calling WebApplication.CreateBuilder(args). We use this builder to build the application by calling builder.Build(), which creates an instance of WebApplication.

app.Use(async (HttpContext context, RequestDelegate next) =>
{
    await context.Response.WriteAsync("Hello 1 Before\n");
    await next(context);
    await context.Response.WriteAsync("Hello 1 After\n");
});
Enter fullscreen mode Exit fullscreen mode

Here, we use the app.Use method to add a middleware to the application pipeline. This middleware takes a lambda expression as a parameter, which defines the code to be executed upon receiving a request. The lambda expression has the HttpContext object and the next delegate as arguments.

In this specific middleware, it writes "Hello 1 Before" to the response, then calls the next middleware in the pipeline using await next(context), and finally writes "Hello 1 After" to the response.

app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Hello 2 Before\n");
    await next(context);
    await context.Response.WriteAsync("Hello 2 After\n");
});
Enter fullscreen mode Exit fullscreen mode

Similarly, another middleware is added using app.Use. This middleware writes "Hello 2 Before" to the response, calls the next middleware, and writes "Hello 2 After" to the response.

app.Run(async (HttpContext context) =>
{
    await context.Response.WriteAsync("Hello 3\n");
});
Enter fullscreen mode Exit fullscreen mode

Finally, a terminal middleware is added using app.Run. This middleware doesn't call the next middleware and simply writes "Hello 3" to the response.

app.Run();
Enter fullscreen mode Exit fullscreen mode

The app.Run method starts the application and begins listening for incoming HTTP requests.

To summarize, this code demonstrates the basic usage of middleware in an ASP.NET Core project. Two middlewares are added using app.Use, each performing some actions before and after calling the next middleware. A terminal middleware is added using app.Run, which doesn't call the next middleware. When the application runs, it will execute the middlewares in the specified order, and the response messages will be written to the browser.

Program.cs

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

// Middleware1: This middleware writes "Hello 1 Before" before invoking the next middleware,
// and "Hello 1 After" after the next middleware has executed.
app.Use(async (HttpContext context, RequestDelegate next) =>
{
    await context.Response.WriteAsync("Hello 1 Before\n");
    await next(context);
    await context.Response.WriteAsync("Hello 1 After\n");
});

// Middleware2: This middleware writes "Hello 2 Before" before invoking the next middleware,
// and "Hello 2 After" after the next middleware has executed.
app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Hello 2 Before\n");
    await next(context);
    await context.Response.WriteAsync("Hello 2 After\n");
});

// Middleware4: This is a terminal middleware that doesn't forward the request to subsequent middleware.
// It simply writes "Hello 3" as the response.
app.Run(async (HttpContext context) =>
{
    await context.Response.WriteAsync("Hello 3\n");
});

app.Run();
Enter fullscreen mode Exit fullscreen mode

Conclusion:

Middleware is a fundamental concept in ASP.NET Core that allows developers to handle requests and responses in a flexible and modular way. By chaining multiple middlewares together, we can achieve a sequence of operations while maintaining the single responsibility principle. In this article, we explored the basic usage of middleware in an ASP.NET Core project and saw how to add and execute middleware in the application pipeline.

In the next article, we will dive deeper into middleware development and explore advanced techniques and scenarios. Stay tuned!

💖 💪 🙅 🚩
anishjoshi1999
Anish Joshi

Posted on July 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related