Middleware in .Net Core

I have read number of articles on middleware and watched some videos and now it’s time to explore it myself.
Here, you will learn how to create and add your own custom middleware into the request pipeline of ASP.NET Core application.

What Is Middleware?

Middleware are small C# components that are assembled into an application pipeline to handle requests and responses. It defines steps that can progress through and each step leading into the next.
It can be used for a wide variety of reasons from Authentication to Logging to Exception Handling etc


Basic Custom middleware

The custom middleware component is like any other .NET class with Invoke() method. However, in order to execute next middleware in a sequence, it should have RequestDelegate type parameter in the constructor.
Visual studio includes template for adding middleware in our application.
Let’s get started by adding one.
For this right click on the project or folder wherever you want to add a middleware and add new Item. Under Web-> ASP.NET you will find middleware template or you search for it.



And it will add a default custom middleware class for you.


Actually there will be two classes one for our custom middleware and another one is extension class which will add the middleware to request pipeline.
The class has RequestDelegate as part of the constructor through DI, the HttpContext gets passed into the executing method and by convention in the Middlware pipeline this is called Invoke.
Notice we have to pass the HttpContext through to the _next delegate call.

Things to consider

The middleware class must include:
  • A public constructor with a parameter of type RequestDelegate.
  • A public method named Invoke or InvokeAsync. This method must:
    • Return a Task.
    • Accept a first parameter of type HttpContext.
    • Can accept additional parameters that are populated by DI

Middleware dependencies
Middleware should follow the Explicit Dependencies Principle by exposing its dependencies in its constructor. Middleware is constructed once per application lifetime.
Middleware components can resolve their dependencies from dependency injection (DI) through constructor parameters. UseMiddleware<T> can also accept additional parameters directly.

Configuration setup


We can use this directly in the Configure method in Startup however it can be cleaner. We can achieve this through defining an extension method which acts on IApplicationBuilder
The recommended way to expose the middleware through IApplicationBuilder and then call them in Startup.Configure.

We can make our startup file more cleaner this way.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseMyCustomMiddleware();
                              
                }

Reference

Comments

Popular Posts

How to position controls using Canvas control in WPF using MVVM

Change font and size in visual studio

JWTs in ASP.NET Core 2.0