Site Loader
Santo Domingo, Dominican Republic
Creando un Middleware Personalizado en ASP .Net Core
Spread the love

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.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>{
        //Make something interesting here
        await next.Invoke();//Paso la solicitud al siguiente middleware
        //Here also I can do more things, like write in a Log or something like that.
    });
}

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:

// Ejemplo de clase middleware personalizada
public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

    public MyCustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext httpContext)
    {
        //Escribo algun codigo interesante aquí
        return _next(httpContext);
    }
}

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:

 

//Agregando nuestra clase Middleware con el método UseMiddleware
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	app.UseMiddleware<MyCustomMiddleware>();
}

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:

 

using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace CustomMiddlewareExample.Middlewares
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class MyCustomMiddlewareWithTemplate
    {
        private readonly RequestDelegate _next;

        public MyCustomMiddlewareWithTemplate(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {

            return _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class MyCustomMiddlewareWithTemplateExtensions
    {
        public static IApplicationBuilder UseMiddlewareClassTemplate(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyCustomMiddlewareWithTemplate>();
        }
    }
}

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!

Post Author: Yeison Angomas

I am a software developer and SEO Analyst with more than 5 years of experience using different technologies. My main skills are the development of web applications in .Net, Oracle and SQL Server.

Leave a Reply

Your email address will not be published. Required fields are marked *