Middleware in ASP.NET Core - Part 1

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there how's everything going if you starting digging into asp.net Colin struggle to fully understand middleware then stay tuned because this video is really for you we'll explain what middleware is how middleware is supposed to work why middleware order is really important and how you can create your very own small but fancy custom middleware so stay tuned [Music] welcome to developer n Papa channel dedicated to anybody who wishes to become a software developer or a better software developer in this video we'll talk about middleware in asp.net core this is a really crucial topic because you simply cannot build an asp.net core application without using at least a bunch of middleware that's why in this video we'll try to graphically define exactly what middleware is how mean how a middleware pipeline is supposed to work and we'll also create our very own custom tiny middleware to see better how this middleware pipeline is supposed to perform actions on incoming requests and outgoing responses so let's start by defining exactly how middleware is supposed to work conceptually let's start by trying to imagine what happens when a request comes in into our web application or API so the request will normally hit our web server which in SP dotnet core is usually kestrel to built-in web server of asp.net core let's name this web server as point a now on the other side there is also a point B which is either a controller if we're having an API and a view if we're having a normal web application the request that comes in has to pass from point A to point B then a response needs to be generated that needs to be again sent to point to point a and then the response will leave our web server so we can imagine the depth between point a and B we have a pipeline so each request will pass through this pipeline from A to B and each response will pass again through the same pipeline from point B to point a now the question would be wouldn't it be very cool if we could have some custom piece of software lying somewhere on the way in this pipeline and that when a request goes to the pipeline it should pass through all this piece of software in which we could perform several things for instance we could have such such a piece of software that performs authentication and authorization we could have another piece of software that would apply logging will log different things we could have another piece of software that would handle exceptions or global exceptions and so on and really that's all what middleware is about middleware is a piece of software that lies on that request pipeline between point a and point B and each request and response needs to pass through all the configured middleware so then we can apply our own custom logic on the incoming request or on the outgoing response so we can imagine that the request would come in it would hit our webserver then it will start to go to the pipeline and it will hit our first middleware which is the authentication and authorization middleware so here is where authentication and authorization will be done if authorization or authentication fails then the request could be terminated here and it could be sent back to point a and then back to the client that made that request however if everything is okay then the request is passed through the neck to the next middleware in this pipeline and in this case is logging so this middleware may look into the headers of the request and check different information and log different things either to the debug console or to a file or a database and when this processing is done this logging middleware will then send the request further to the next middleware in the pipeline which in our case would be the exception handling middleware so if we have a problem for instance a request for a page that doesn't exist or an endpoint that doesn't exist we can choose to terminate the request here and the response will be generated and sent to the client via point a however once again if everything is alright then the request would arrive to our controller of our viola T then what happens here is that a response is generated if we have an API this might be a JSON response if we have our application the response would contain an HTML page and then the response is sent again through this middleware pipelining it passes all the exact same middleware but in reverse order so it will pass the exception middleware first and here again if we need to perform our logic and log some exception based on the response that we have received from point B we can do that here then of course we could apply also login authentication and authorization will be on the response probably not necessary so the authentication middleware will simply pass the request further so the request will arrive to the web server and it will be sent to the client and the client would receive the awaited response so that's a very basic explanation on how middleware is supposed to work and because requests are passing one by one through all this important middleware in the pipeline we can see that also or we can assume that middleware order is really very important because each request will pass through each middleware in this exact order and it responds will pass through the exact same middleware but in reverse order since it starts from point B so for instance if we are placing the logging middleware and exception middleware before the authentication middleware maybe we will perform some logging operations or exception throwing throws on a request that it not that is not authorized or authenticated and in this case we have basically used some resources that we don't need so that's wide the authentication and authorization middleware usually is one of the first pieces of middleware that you would configure in a middleware pipeline let's switch back to visual studio to see exactly how we can implement middleware in an asp.net core application I have started a brand new asp.net core API project however if you want to follow along you can start an asp.net core empty project or a web project it is the same for our proposed and we are here on the startup dot CSO on the startup class because here is where we'll work with middleware we have this configure services method which we'll skip for now because we want to concentrate on this configure method because in this configure method as these comments also show is used to define middleware so to apply custom logic to incoming requests and outgoing response and by default when you start a new project you already have two middleware configured I'm sure you already have seen this if if you have played around with asp.net core but maybe you did not realize that what you see here is basically middleware so a first middleware is app use developer exception page which basically means that when we are running this application in and development environment we will use always developer friendly exception pages then the second piece of middleware that we have is use MVC which instructs the asp.net core application to use the MVC model so if we have controllers then request would be routed to our controllers and so on however we can customize your or configure different type of middleware and there is or there are some middleware pieces that are shipped directly with asp.net core and one of them is for instance use authentication and this would configure a middleware that would be able to authenticate and authorize the incoming request and as said usually we want perform authentication and authorization as fast as possible so that's why this middleware will usually be here right after the huge developer exception page middleware then we can have other type of middleware that would perform other things like use course and this middleware is used to configure cross-origin resource sharing now we have here a red squiggly line because a lot of of the middleware that comes in with asp.net core needs to be also configured so when we run use course we also need to provide a configuration object and so on but for now we won't bother about this red squiggly line I just wanted to show you that you could implement this type of middleware then another one that is a very common is use static files and we always need this middleware if we really want to serve also static files to incoming requests and if the request is for a static file it doesn't need to pass through all the other middleware that that comes afterwards we can just simply serve the static file that is needed and of course we can configure exactly from where to serve the static files and so on the main idea is if you remember this this graphical representation with point a and point B let's assume that point a a is here somewhere above let's say this is point a and let's assume that point B is somewhere here after use MVC so when a request comes in what it will happen it will come we could say as example from above and it will hit each middleware one after the other when the response is generated the response will again pass through each of this configured middleware in reverse order so it will pass through use MVC you static files use course use authentication however when we already have the response we usually want before any actions here the main idea is that on if you write your custom middleware for instance you can define a certain actions to be performed when the request comes in and then await the response and perform some further actions when the response is already available very important is to note that here in this configure method is where you configure your middleware pipeline and the order is very important each request will start with the first middleware then the second the third and so on and the response will then a pass to the same in our pipeline but in reverse order let's now take a look at how we can configure our very small very tiny custom middleware here so that we can show better how middleware is supposed to work please note first that we have removed all previously configured middleware since we really don't need them anymore we want to concentrate right now on our custom middleware because because using our custom middleware we can also see better how the middleware pipeline can become configured so a custom middleware can be always used using epidote use use is a delegate on the a application builder instance that will help us to perform some custom logic here on the request or on the response and then pass it to the next middleware in the pipeline in order to do that we would need basically two very important things let's first of all make this async everything what comes afterwards and we would need the HTTP context and the next delegate and I will shortly explain also why we need that and we used a simple lambda expression in order to run some custom logic here now the next delegate is very important because we will use it in order to instruct the request or to send the request to the next middleware in the pipeline and the context is the placeholder for the current HTTP context that we will have on each request so what we'll do here is a wait context dot response dot write async and here we will simply write something and also let's add P tag this would be an HTML tag okay we have also to provide here P and then let's oh here run hello world a very very basic I would say traditional hello world output and here what we need to do is also to use the next delegate and using this next delegate will simply pass this request or the response to the next middleware in the pipeline if we want to pass it to the next middleware and we are working currently on the request it will be passed to use MVC if we would do something on the response then it would be passed here to use developer exception page however let's make some things a little bit clearer let's add a comment here so this is logic to perform on request normally and after this wait dot next we would have logic to perform on response so this is how you would normally do it this means that this wait context response write async called we should normally make here after the await next however for testing purposes we want to run this here in the part where we would normally process the requests and we will see exactly also why when we run this application we will also get some exceptions but we could already test how this middleware is working right now and the application is starting in few seconds we'll see some output in the browser and it is hello world as expected so that's perfectly fine and here are also the exception that we got because we wrote to the response before the response was even generated let's say good let's here however simply copy this middleware and edit once again and let's change here a little bit and let's make it hello from middleware 1 and here let's put hello from middleware - ok so now we should have two outputs in our browser one from the first middleware and one from the second middleware so let's check if this this is truly the case and in a few seconds we should be able and indeed we have hello from middleware one and hello from middleware two so that's kind of cool we created two custom middleware one prints hello from Italy where one and the second prints hello from middleware too but what happens if we simply delete these ways next we said that a wait next was basically sending the request to the next middleware in the pipeline so let's run the application and check exactly what the behavior is and when the application loads we will see that the result should be a little bit different but how different oh we can see here we have only hello from middleware one which means that only this middleware was executed and this means in turn that if we don't use this await next then the request will won't simply be sent further to the next middleware in the pipeline and the response will be generated and will be returned to the client so in this case the app the second EPCOT use was never hit because we don't have next if we introduce here wait next then we would see that everything should be fine again so we can safely say that this next delegate is very important because if we don't use it we can short-circuit the entire major oil pipeline now for instance this might be useful in some cases for example you have to perform some custom logic and if certain ticks don't add up you simply want to generate a response and return it to the client without passing the request to all the other middleware in the pipeline but in most cases when you are using app dot use you want to pass the request further to be processed so don't forget it's very important always if you are using this app to choose to add some custom logic your custom your custom logic to the middleware pipeline don't forget to add this away store next or await next sorry so we have seen what middleware is what amygdala where pipeline is how we can configure a middleware pipeline how we can use default built-in middleware that fit together with asp.net core and finally we have created our own custom middleware one middleware to print hello from middleware one and the other hello from middleware two finally we have tested what happens if we simply forget to add the next delegate to app don't use middleware and it will simply short-circuit the pipeline now since this video got fairly long we will stop for now here but there will be a continuation to this video of part 2 where we will talk about other app delegates for now we have used only abused but we can also use app run and this will also short-circuit the pipeline and we can use app map or app map when and in that case we can configure different maps in certain circumstances so please check again shortly to see the second video about asp.net core middleware if you find this content useful please subscribe to develop a ramp up feel free to share this content with your friends and network also and should you have any feedback or questions just hit me with a comment also don't forget at times up thank you very very much for watching and until the next time I wish you the very best
Info
Channel: Codewrinkles
Views: 12,736
Rating: 4.9264708 out of 5
Keywords: ASP.Net Core, DotNetCore, C#, web development, software development, programming
Id: HCxAERjO4C4
Channel Id: undefined
Length: 21min 3sec (1263 seconds)
Published: Thu May 03 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.