Tutorial of How to Create a Custom Middleware in ASP .NET Core [New Guide with Examples]

Tutorial of How to Create a Custom Middleware in ASP .NET Core [New Guide with Examples]

Although ASP .Net Core has numerous predefined middleware, which can be added to our application with great ease and without the need to add complexity to our code, in many cases we will have to define certain functionality add through a middleware.

For this reason ASP.Net Core allows us to add our own custom middlewares in case we consider necessary.

Without further ado let’s see how we can do this.

How to Define a Custom Middleware?

There are two ways to do it:

Using an anonymous method also called inline middleware or online middleware.

Creating a middleware class that contains the methods that will be invoked once a request is received.

Below are some examples of how to create each one.

Example of Customized Online Middleware (Anonymous Method)

This example shows how you can create a middleware using an anonymous method which receives as parameters an HttpContext object and a delegate to which you can call the next middleware to process the current request.

Example Creating a Custom Middleware in a Class

It is recommended that when defining a custom middleware it is that we create a separate class, because this allows us to have greater portability and organization within our project.

To create a middleware class we simply define an Invoke method and create a constructor that receives a RequestDelegate object as a parameter. See an example:

Then we only have to define our middleware in our Startup class so that it can be used in each application. You can do this easily using the UseMiddleware method that it finds in the IApplicationBuilder interface. See an example:

Simplify everything using Method Extensions

It is also advisable to define method extensions to simplify the declaration of our custom middleware in the Startup class. This can be done simply by defining a new class with an extension method that has this definition.

Then we should just call the extension method that defines our middleware in the Startup class from the Configure method.

Creating Middleware Using a Visual Studio Template

You can also save time and create your custom middleware using a Visual Studio template, where you just have to right click on the folder you want to create your middleware and click on Add -> New File. Then look for the template called Middleware as shown below:

Visual Studio will generate a middleware class similar to the following:

You just have to add the logic you want to implement in the Invoke method.

And ready!

You already have a custom middleware with a very clean and organized code structure.

I hope this tutorial has helped you on how to create your own custom middleware.

If you have any questions or suggestions let me know in the comments.

And see you in the next post!

Leave a Comment