Understand Middleware in .Net Core

by | Sep 6, 2023 | .Net Core, Learn | 0 comments

What is Middlewares in .Net Core

Middleware is a piece of software that handles http request and response.

In simple term, .net core works with middleware in order to enhance performance of our application rather than having big chunk of framework component/ libraries at once, for which most of the http requests, it’s not even useful.

Middleware is modular

Whenever request comes, it is forwarded to middleware, to perform some tasks related to request context. It then can pass request to do some further processing. .Net Core, we can have many middleware’s configured in pipeline, each one is responsible to perform related tasks like logging, authentication, serving static files, MVC etc. So, it follows the “single responsible principle” and provide modular way of configuring application. We can simply remove middleware which we do not required for some specific type of requests, in that way our application becomes so light.

 

“You only pay for the for the middleware components you have in your application request processing pipeline!”

 

  • Every middleware has control – Incoming request, and outgoing response.
  • Middleware component pass request to next middleware in the pipeline

Ex- one middleware does some processing, and then pass the request on to the next middleware for further processing.

  • Middleware component may handle the request and short circuit the rest of the pipeline

Ex – if request is for serving static file, then no need to go to next pipeline, like MVC. It should stop. We can achieve that in .net core.

  • Executed in the order they are added to the pipeline.

 

Other Advantages of Middleware

 

  • Selective execution: With .NET Core middleware, you have the flexibility to choose and include only the middleware components you need for your application. This means you can avoid unnecessary processing and reduce the overall overhead. In contrast, the .NET Framework includes a comprehensive set of features, which may result in executing code that you don’t require for your specific application, potentially impacting performance.

 

  • Asynchronous processing: .NET Core middleware is designed to take full advantage of asynchronous programming patterns, such as async/await. This allows for non-blocking I/O operations, enabling concurrent processing of multiple requests. Asynchronous processing improves the responsiveness and scalability of your application, especially under high load scenarios. The .NET Framework also supports asynchronous programming, but .NET Core provides better optimizations and tools for managing asynchronous tasks.

 

  • Optimized request pipeline: The request pipeline in .NET Core middleware is designed for improved performance. It incorporates various optimizations, such as a lightweight execution model, efficient routing, and built-in features like response compression and caching. These optimizations help minimize latency and improve the overall speed of request processing.

 

  • Improved platform compatibility: .NET Core middleware has been built with cross-platform compatibility in mind. It is designed to work seamlessly on Windows, Linux, and macOS, taking advantage of platform-specific optimizations. This flexibility allows you to choose the best hosting environment for your application and optimize performance based on the target platform.

 

  • Enhanced development practices: .NET Core promotes modern development practices, such as dependency injection, which helps manage dependencies more efficiently and improves code maintainability. It also encourages the use of lightweight frameworks like ASP.NET Core, which provide better performance and enable you to build highly optimized web applications.

 

Configure Middleware

 

In Startup.cs there are two methods

  1. ConfigureServices”

 

The ConfigureServices method is responsible for configuring the services that your application will use. This includes registering dependencies, configuring dependency injection, and setting up various services needed by the application. Middleware-specific configurations are not typically done in this method, but it plays a crucial role in the overall configuration process.

 

  1. Configure:

 

The Configure method is where you configure the middleware pipeline for your application. This method defines the sequence of middleware components and their respective configurations. The middleware components are added using the app parameter of the Configure method, which is an instance of IApplicationBuilder.

Here’s an example of how to use the Configure method to add middleware components:

In this example, several middleware components are added to the pipeline:

 

  • UseDeveloperExceptionPage and UseExceptionHandler handle exceptions and provide developer-friendly error pages.
  • UseHsts adds HTTP Strict Transport Security (HSTS) headers for enhanced security.
  • UseHttpsRedirection redirects HTTP requests to HTTPS.
  • UseStaticFiles serves static files like CSS, JavaScript, and images.
  • UseCookiePolicy sets up cookie handling.

 

You can also add custom middleware components or third-party middleware by using the app.Use method and passing in the middleware component.

Remember to add the necessary using statements at the top of your Startup.cs file for the middleware components you want to use.

By configuring the middleware pipeline in the Configure method, you define the order in which middleware components are executed and the specific configurations applied to each middleware component.

How to add middleware components to the application’s request pipeline

1. app.Run Method:

The app.Run method is used to add a terminal middleware component to the request pipeline. It takes a RequestDelegate parameter that represents a delegate that handles the request. The delegate receives an instance of HttpContext and is responsible for generating the response.

Here’s an example of using app.Run to handle a request:

 

In this example, when a request comes in, the delegate defined in app.Run will be executed, and the response “Hello, World!” will be sent back to the client.

2. app.Use Method:


The app.Use method is used to add middleware components to the request pipeline. Middleware components added with app.Use are non-terminal, meaning subsequent middleware components in the pipeline will also be executed.

Here’s an example of using app.Use to add a middleware component:

app.Use(async (context, next) =>
{
// Do something before the next middleware component
await next.Invoke();
// Do something after the next middleware component
});

In this example, the delegate passed to app.Use is responsible for processing the request and invoking the next middleware component in the pipeline by calling next.Invoke().

 

3. app.UseMiddleware: Method

The app.UseMiddleware method is another way to add middleware components to the request pipeline. It allows you to use custom middleware classes in your application.

Here’s an example of using app.UseMiddleware to add a custom middleware component:

In this example, CustomMiddleware is a custom middleware class that you have implemented. It should implement the IMiddleware interface or have a method with the signature Task InvokeAsync(HttpContext context, RequestDelegate next).

 

4. app.Map and app.MapWhen Methods:

The app.Map and app.MapWhen methods allow you to map specific request paths or conditions to different middleware branches. This enables you to apply different middleware components based on specific route patterns or conditions.
Here’s an example of using app.Map to map a specific path to a middleware branch:

 

In this example, when a request comes in with a path starting with “/admin”, the AdminMiddleware will be executed.

These are some of the key methods used to configure middleware components in the request pipeline of a .NET Core application. By utilizing these methods, you can define the sequence of middleware components, handle specific routes or conditions, and customize the behavior of your application.

 

Thanks for reading, do not forget to put comments and suggestions

app.UseMiddleware();

0 Comments

Related Posts

Delegates in C#: Complete tutorial

Learn Delegates c# In C#, a delegate is a type that represents references to methods with a particular parameter list and return type. Delegates provide a way to encapsulate a method, and they are often used for defining callback methods and implementing event...

Inheritance in C# oops complete guide

Inheritance Table of content: Topics1Why i wrote this article2Inheritance - complete guide3All possible scenarios based/ tricky in/out type of Interview questions Why i wrote this article? When I was preparing c#/oops, the main challenge was information was scattered...

Learn Angular Directives

Angular Directives Angular directives are an essential part of the Angular framework, allowing you to extend the HTML vocabulary to build dynamic and interactive web applications. There are three main types of directives in Angular: Components: Components are the most...

.Net Core Garbage Collector

Garbage collection   Garbage collection (GC) in .NET Core is an automatic memory management technique that reclaims unused memory. It simplifies memory management for developers and reduces memory leaks and bugs.   The GC identifies and collects objects that...

Most Useful Git Commands

Git commands you should know: git init: Initializes a new Git repository in the current directory. git clone [repository_url]: Creates a copy of a remote repository on your local machine. git add [file]: Stages changes for commit. You can use git add . to stage all...

.Net Core Introduction

INTRODUCTION .NET Core is a modern, cross-platform, and open-source development platform developed and maintained by Microsoft. It provides developers with a fast, flexible, and modular framework for building applications for Windows, Linux, macOS, iOS, and Android....

Delegates in C#: Complete tutorial

Learn Delegates c# In C#, a delegate is a type that represents references to methods with a particular parameter list and return type. Delegates provide a way to encapsulate a method, and they are often used for defining callback methods and implementing event...

Inheritance in C# oops complete guide

Inheritance Table of content: Topics1Why i wrote this article2Inheritance - complete guide3All possible scenarios based/ tricky in/out type of Interview questions Why i wrote this article? When I was preparing c#/oops, the main challenge was information was scattered...

Learn C# oops Polymorphism

Polymorphism Simplifying Polymorphism in C# with Examples Polymorphism is a fundamental concept in object-oriented programming (OOP), and it can be understood more easily by breaking it down into its key components. What is Polymorphism? At its core, polymorphism...

Learn Angular Directives

Angular Directives Angular directives are an essential part of the Angular framework, allowing you to extend the HTML vocabulary to build dynamic and interactive web applications. There are three main types of directives in Angular: Components: Components are the most...

.Net core Fun FACTS to choose other backend but NOT .Net Core

Funny Excuses to Avoid Learning and Using .NET Core for Your Next Backend Web API (And Why You Should Consider Node.js and Other Popular Alternatives Instead) In the world of backend web development, there are numerous technologies to choose from. One option that...

.Net Core Garbage Collector

Garbage collection   Garbage collection (GC) in .NET Core is an automatic memory management technique that reclaims unused memory. It simplifies memory management for developers and reduces memory leaks and bugs.   The GC identifies and collects objects that...

Most Useful Git Commands

Git commands you should know: git init: Initializes a new Git repository in the current directory. git clone [repository_url]: Creates a copy of a remote repository on your local machine. git add [file]: Stages changes for commit. You can use git add . to stage all...

Commonly used commands for .net Core Good to remember

Most userful commands for .net Core. Good to remember. dotnet new: This command is used to create a new project based on a specified template. It generates the basic structure and files required for a .NET Core application. Example: dotnet new console dotnet clean:...

.Net Core Introduction

INTRODUCTION .NET Core is a modern, cross-platform, and open-source development platform developed and maintained by Microsoft. It provides developers with a fast, flexible, and modular framework for building applications for Windows, Linux, macOS, iOS, and Android....

.Net Framework Basics CLR CTS CTS MSIL

CLR (Common Language Runtime) Responsible for program execution in .Net Framework Some crucial role of CLR- Memory Management: The CLR is responsible for managing memory allocation and deallocation in .NET applications. It includes automatic memory management through...

.Net Core vs .Net Framework differences

CLR vs Core CLR What is CoreCLR The CoreCLR provides many similar functionalities as the CLR, but it is specifically designed for the cross-platform nature of .NET Core. General CLR feature includes features like Just-In-Time (JIT) compilation, garbage collection,...

Learn How .Net Core Hosting Works

Hosting In .NET CoreIn ASP.NET Core, there are two hosting models available: in-process hosting and out-of-process hosting.In-process Hosting (Default): In the in-process hosting model, a single web server (e.g., IIS) is used directly to host the application. To...