How to use Middleware in ASP.NET Core (2 ways of implementing middleware)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to dotnet core central in today's video i'm going to discuss about middleware in asp.net core middleware in asp.net core is nothing but components that are assembled into the http pipeline to handle requests and response now a middleware component can either choose to pass the request to the next component in the pipeline or it may choose to end the request it depends on the requirement of the middleware now a middleware can perform the task both before as well as after calling the next component the way it works is if you look into the diagram when a request comes into the http pipeline it goes into the middle where the middleware executes before sending it to the next middleware then it sends the request to the next middleware and this way the request travels through multiple middlewares and then finally the last middleware sends the response back and all that middleware can either choose to handle the response do something with it or just let it go that is how this works now the middleware in asp.net core are very similar to the way i http handler and i http module worked in the legacy asp.net application now the only difference is i http handler was the last endpoint at the http pipeline whereas i http module were more like filtered through the pipeline the middleware in sp.cor works as both it can either work as like i http module meaning the request can go and come back and it doesn't end the request meaning it is not acting as the last endpoint of the middleware chain or it might choose to decide the end point of a middleware chain and i'm going to show how this works now the middleware functionality are achieved using two ways one is there are out of box extension methods on eye application builder which can be used for creating middleware and those methods are there are mainly three kinds of methods one is a run the second one is use and the third one is map and i'm going to go through all of them one by one and the other way is to write own custom middleware and i'm going to show that as well so to do that let's start with asp.net core application now i'm going to create a new asp.net core web application and i'm going to name it as middleware.demo and i'm going to go ahead keep asp.net code 3.1 and i'm just going to create an empty project now once the project is created i'm going to keep the main method as is because we're not doing anything here now in the startup what i'm going to do is i'm going to get rid of all this code because i'm not using any routing nothing we're going to start with these middleware so let's say we also don't need the iwebhost environment so i'm just going to get rid of it so first thing we can do is we can do app.run and if you look into the definition of run it says it adds a terminal middleware delegate to an application requests pipeline meaning nothing will go beyond this point once this middleware is hit anything below this middleware will never be executed and i'm going to show it and here we can do context dot response dot write sync and in the right we can say response from fast middleware and then we can write another app.run and i'll just copy paste the same thing and here we can say second middleware let's just give a break okay now let me change it to run as a console so now let's run this application now when we run this application you can see that the response comes only from the fast one because as i explained before it's a terminal middleware meaning after a run is executed nothing else below that will ever be executed so now that brings us to the next extension method for middleware which is use now when we use the method use it takes as you can see it has a http context and it takes a func which is the delegate to the next middleware so here in this case if we don't use the next then it will behave exactly like run so let me show what i mean by that if i run it now it will just execute the first one because we are not executing next so the next middleware will never be executed so it will act as a terminal middleware see only the first one is printed but if we just do await next now what will happen is after it executes the first one it will execute the next one also and as you can see it executed the first one and then the second one so let me do one thing let me just give here html body and let's close the html here okay now if i run they should be in two different line yeah so the first one and second one the next thing i wanted to show as i mentioned earlier that middleware can have logic before as well as after calling the next middleware so to demonstrate that what i can do is i can add a weight here and let me just copy paste this line and here what i can do is i can leave this as is and this the after code can act as a and for the fast middleware as well as the closing for html and the body so now if i run this i forgot to give a break but you can see response for fast middleware response from second middleware and then end of fast middleware they're getting printed as expected now that we have seen the run and use let's go to the next one and to show the next one i'm going to show you the other variation of use which is use when so if i do a app dot use when you can see in the description itself it conditionally creates a branch in the request pipeline that rejoins to the main pipeline now this is very important the point of rejoin the main pipeline what it is essentially saying that when we have a condition it will create a branch for the request and whatever we have in the branch will be executed but then it will come back and join the the main branch of the http request pipeline so now if we do a use when and we created a branch here and as you can see it's a func which takes a context and return a bool so we can have something like context and we can say if context dot request dot query string contains a key let's say the key is roll so we are saying if the query string contains role then create a new branch okay and this rio branch we are basically getting a handle to the same i application builder so we can take that and it's an action and once we get the i application builder we can do anything that we want we can use a use or run so let's use a run because we want to terminate this branch so we can say async context and here we can have we can just copy paste one of this line and here we can say roll is let's break this one also so you can say roll is context dot request dot query row and that's about it so now if i run and if i add a query string here roll equal to admin now you can see it did the fast middleware then it did the roll as admin and because this is a terminal middleware then it is just going to go back to the fast middleware and print the end which is unexpected behavior so that's with use when the next one i want to show is map so for map as the name suggests it basically maps to a path so you can see it creates a branch for the request pipeline which matches the path so now we can have let's say it maps to map and then again just like before with use when it gets uh i application builder and then after that basically we create a branch and we can do whatever we want so let's do this let's create a a dot run and here we can just say instead of these we can say new branch map now if we run this and if we say slash map you can see that it is going to the new branch okay the other thing we can do basically and this is where it gets interesting and powerful is that now we can have multiple branches which means that inside of the map itself we can map other endpoints and those endpoints are going to be sub-level branches here we can say a dot map so we're essentially creating another branch inside of the slash map so here we can say branch and we already used app as well as a so here let's use x and then we can say x dot run and instead of run we can say again request on and alert so you can say async context plus 2 and we can just copy paste this line and we can say new branch this is the child so we can say new child branch and close it so if i do that now i created essentially another branch inside of map so i can either go to map or we can go to map slash branch so if i go to just map will show that we are in new branch map and if i go to map slash branch it will show that we are going inside of neutral and as you can see since i use the run which is the terminal middleware after the child branch it's not going to print back the parent branch so that's with the map and similar to map we can have map when map when and use when are very similar both are used with a conditional operator the only difference is used when can join back the main branch whereas map1 will never join back the main so it's very similar as you can see it takes the same exact same syntax so we can i'm just going to copy paste this whole thing and i'm just going to change the name of the query string from roll to something else count and count is count so if i have to show that i can just go here now if i do uh now you can see count 5 is printed so it is very similar to how the use one works now it's time to show how to build a custom middleware but before i do that what we can do is we can just create an extension method on the i application builder itself and move all this code there so for that i'm going to create a new class and i can say app middleware extensions and inside of that i can fast create my extension method i can say public static let's make this class also static void add just for the proper naming convention i'm just going to say use extensions these i application builder app and then what i can do is i can just copy paste all this code here that's all and then next let me add the namespace get rid of the unwanted namespaces okay and then here what i can do is i can just do app dot use extensions and now if i run this application i'm going to see the same behavior as before i just moved the code into an extension method that's all i did this is just to show that how you can just clean up the code a little bit now let's get into building a custom middleware now for building custom middleware the way it works is there are two parts of the equation one part is we create a class with a convention meaning the convention is it has to have a public async invoke method which takes an http context as an input and in the constructor it takes a request delegate next as a constructor parameter the request delegate is nothing but the handle to the next middleware in the pipeline and then in the startup we can use the use middleware extension method it's a generic extension method and we can pass the new type to the generic extension method so let me show it so let's create a new class called custom middleware so i'm going to go ahead and add a new class and i'm going to name it as custom middleware in the class as i mentioned it will have a constructor which will take the request delegate next as the next endpoint and i can just create it as a local variable to the class and the next thing is i'm going to have a public async task invoke as i mentioned earlier it's a conventional based programming so it's going to take http context and then here now that we have http context we can do whatever we want with the context so just for simplicity we can have await http context.response.writeasync and we can write something here so we can say inside and let me get rid of this so we can say inside the new custom middleware and then we're going to call the next milward in the pipeline i have to pass the http context to the next now this is done let me get rid of the unwanted namespaces now what we have to do is we have to go into startup and here instead of using extensions we can call the use middleware method and as you can see it adds a middleware type to the applications request pipeline so we have to pass the type and our type is custom middleware and since i am calling the next middleware in the pipeline what i can do is i can do app dot run and here i can say async context context dot response dot write async and i can just say and so now if i go ahead and run this application i can see that inside the new custom middleware and since i'm calling the next delicate it is going to say end which is the last statement that i have the other advantage of type based middleware is if we have other items injected inside it it will automatically pick up just to show that what i can do is i can create a i my type my type and i can generate the imi type and let me initialize and imi type is an interface and let's say it has public word print so and i can declare a my type which implements imitate so it's just console.writeline let me change it i don't like i my type we just name it as i printer and let's rename this as printer so it has print and here just printing so now here we have eye printer and we can change this printer let's change this also and here we can just say it's a printer dot print and then what we can do is we can go back to startup and here we can say services dot add singleton and we can say i printer printer that's all and now if i run this application what is going to happen is the new class that i created it will get and handle off and see it is printing now it is printing twice because it's a print statement so it will execute both the time while coming in as well as going out that's about it so that's the main advantage of using a custom middleware as a class is that if we have a lot of logic we obviously don't want to put all the logic inside of this class so we can have multiple interfaces and we can inject them and then we can use it inside of the invoke method to do some custom logic so i guess that's all i wanted to cover today i'm hoping that it covers most of the fundamentals of middleware if you like this video please give me a thumbs up and if you are not subscribed to my channel and you think you are getting value out of my channel please subscribe to my channel and thank you very much for watching this video
Info
Channel: DotNet Core Central
Views: 24,922
Rating: undefined out of 5
Keywords: middleware, middleware in asp.net core, middleware in .net core, middleware extension method, middleware extension method run, middleware extension method use, middleware extension method map, asp.net core middleware
Id: iR_PNKtJENE
Channel Id: undefined
Length: 17min 58sec (1078 seconds)
Published: Mon Aug 10 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.