Enable Javascript

Please enable Javascript to view website properly

Toll Free 1800 889 7020

Looking for an Expert Development Team? Take 2 weeks Free Trial! Try Now

Middlewares in .NET Core 3.1

Agenda

In this article, we will learn about the concept of Middleware, which is introduced by .NET Core team.

Pre-requisites:

  • .NET Core 3.1 SDK
  • Visual Studio code
  • Basic knowledge of the pipeline architecture of .NET Core 3+.

What is a Middleware?

A middleware is a piece of logic or code, that can be injected in the request-response pipeline of a .net core application development services.

The HTTP requests in the pipeline are managed by Request Delegates which can be configured using three extension methods.

  • Use This is used to allow the request delegate to pass the request to the next middleware in the pipeline.
  • Map This branch the request pipeline with the mentioned URL In simpler words, this should be used in some specific cases where you want to map something to a special URL.
  • Run This will be used to end the pipeline registrations and acts as a final step. In simpler words, this should be used at the very last step of the pipelines when you want to start the actual application.

Middlewares are registered in the Startup.cs file in a .NET Core application. Configure method handles all HTTP requests. You can register as many middlewares as you need, but the ordering is important.

Let’s move to the demo now for better understanding.

Step 1: Install .NET Core 3.1 SDK from Microsoft’s official website.

Middlewares .NET Core

Install the SDK from the downloaded installer.

Step 2: Install Visual Studio Code editor. Please go to https://code.visualstudio.com and download the installer based on your OS Type.

Middlewares .NET Core

Step 3: Let’s create a new .net core project in Visual Studio code. Create a folder at C:\Demos\DotNetCoreMiddleware. Open this folder in VS code as shown below.

Middlewares .NET Core

Step 4: We need to install an extension in VS Code which will activate C# features in VS code. So, install C# extension mentioned below.

Middlewares .NET Core

Step 5: Create an ASP.NET core web application using integrated terminal. Press Ctrl+~ to open integrated terminal.

Command: dotnet new webapp

Middlewares .NET Core

Step 6: Below is the startup.cs file where some of the in-built middlewares are already registered with the new project template.

Middlewares .NET Core

We can also create a custom middleware which contains our own custom logic and we can register it here.

Below is the example of in-line middleware registration.

Since we are using app.Use extension method, first declaration will execute the reponse line and then passes the execution to the next middleware using next() object.

Note: For better understanding, do read the comments mentioned in the screenshot below against each line.

Middlewares .NET Core

Below is the example of app.Run extension method which will end up the request pipeline registrations.

Middlewares .NET Core

Now, let’s run the application and see the response.

Open the integrated terminal and hit the following command: dotnet run

Middlewares .NET Core

As you can see the reponse in the above screenshot, the 4th middleware is not executed.

Now, if we convert 3rd middleware to app.use method, then 4th middleware will work. Below is the screenshot with code changes.

Middlewares .NET Core

Now, I hope that you understood that how middlewares work.

Let’s create a custom middleware which resides in a separate folder and file and see the example that how to register them in request pipeline.

Create a folder with name Middleware and create a new file with the following name.

Middlewares .NET Core

Now, copy the following code in the newly created file.

using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; public class CustomLogicMiddleware { private readonly RequestDelegate _next; public CustomLogicMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext httpContext) { await httpContext.Response.WriteAsync("My Custom Logic Middleware created in separate file.\n"); await _next(httpContext); // calling next middleware } } // Extension method used to add the middleware to the HTTP request pipeline. public static class CustomLogicMiddlewareExtensions { public static IApplicationBuilder UseCustomLogicMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware < CustomLogicMiddleware> (); } }

As you can see in the above code, RequestDelegate is used which will allow other middlewares to execute after the execution of this middleware.

We also created a static class at the last, which will register the middleware in the IApplicationBuilder container so that Startup.cs file can access this new method.

Now, I have registered this custom middleware before the app.Run method in startup.cs file.

Middlewares .NET Core

Let’s re-run the application and see the response.

Middlewares .NET Core

See the flexibility that .net core provides us. This will surely help each and every hire ASP.NET developer to follow the SOLID principles.

Software Development Team
Need Software Development Team?
captcha
🙌

Thank you!
We will contact soon.

Oops! Something went wrong.

Recent Blogs

Categories

NSS Note
Trusted by Global Clients