Understanding Middleware in ASP.NET Core – Part 3

In this section, we are going to build our own middleware extensions and try to utilize the same in our code. I have created one folder for the same. Below is the glimpse for the same.

28th

I have created one sample middleware and below is the snippet for the same.

30th

Here, first thing comes constructor which has the reference of RequestDelegate next. This means this component will be able to invoke next middleware in the pipeline. After constructor, we have definition which allows us to invoke our middleware.  Here, we have very simple custom middleware class. Now, in order to use the same in our application with appBuilder extension methods, we need to expose the same as extension. Therefore, Let’s go ahead and write extension for the same. Extensions, I’ll be keeping in a separate folder just for the sake tidiness.  Now, my folder structure goes like this.

31th

And my extension method which I have written on top of IApplicationBuilder just to make sure that it should be available like other extension methods.

32nd

Off-course,  I am using one generic method to return my custom middleware here “UseMiddleware<>“. With that being said, let’s consume the same in our app.

33rd

With above changes done, when I run my app, it will come something like this.

35th

However, when I run some other middlewares like MapWhen, then it will produce following output.

34th

I hope middleware chaining is clear now. In coming sections, we will delve further. Thanks for Joining me.

Thanks,
Rahul Sahay
Happy Coding

1,525 total views, 2 views today

2 thoughts on “Understanding Middleware in ASP.NET Core – Part 3

Comments are closed.