FILTERS In ASP NET Core | Getting Started With ASP.NET Core Series

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
filters in asp.net core allow code to be run before or after specific stages in the request processing pipeline there are built-in filters like the ones used for authorization response caching etc you can also write custom filters for handling crosscutting concerns like configuration logging exception handling etc in this video let's learn more about filters in asp.net core how it works how it's set up and how to write a custom filter from scratch hello everyone my name is rahul and welcome back to this youtube channel if you're new here i make videos around dotnet cloud and devops if this is of interest to you please make sure to subscribe this channel it definitely helps me to grow this youtube channel without much delay let's dive straight into asp.net core filters filters run within the asp.net core action invocation pipeline sometimes also referred to as the filter pipeline the filter pipeline runs after the asp.net core selects the action to execute looking here at the high level request pipeline you can see there is a request coming in where the other middlewares gets executed first and then the routing middleware followed by choosing the action once the action is selected it heads off into the filter pipeline this is where the various filters gets executed so usually there is code that gets executed before the action and also after the action as part of the filter pipeline let's look at this by setting up a new application and creating some custom filters let's head off to my console and start creating a new asp.net web api application so let's use the dotnet cli specify new and specify web api to create a new web api in the current folder this creates a new application using the dotnet cli let's use rider as the ide in this example and specify dot to open the current folder along with the project inside it i have the project opened in ryder you can see the project and you can see the normal files which are the program.cs the startup.cs and also the controller which is the weather forecast controller this is the default structure that comes as part of the template that we used let's create a new class and call this my sample action filter so this is going to be the custom filter that we are going to create to create a custom filter we need to implement an interface in this case since this is an action filter let's use i action filter so there are two methods as part of this interface that needs to be implemented so that is the on action executing and the on action executed so let's add these implementations and start writing the code for that to understand the request pipeline and how it works let's start writing console statements within these functions so this will help us to log it and see how it's getting executed so let's remove this and say console.writeline and specify the action name itself so in this case i will specify on action executing similarly let's copy this and replace this method to say on action executed to register this filter in the asp.net core pipeline let's head off into the startup.cs class we can setup the filter under the configure services method this is where the dependency injection and all the asp.net core related services are set up i had done a complete different video on how this works and how this setup is done make sure to check that out if you are new to it the add controllers method also has an overloaded function which takes in an mvc options as a parameter so let's use that to configure the asp.net core filter pipeline so let's take in our options parameter and specify the delegate function inside here we can use the options and specify the filters.add method to add a new filter inside here so let's specify new my sample action filter in this case because this is the filter that we just created this adds the sample action filter into the asp.net request pipeline let's run this application and see this filter in action the application is running and it has hit the swagger endpoint which is configured by default in the template we can go into the get method and try this method out so let's click execute now this is going to execute this specific endpoint to get the weather forecast and it has returned some dummy data if we go back to rider and look at the console statements here we can see this has now logged the on action executing and also the on action executed so our filter has got successfully invoked when we called the get method if you are new to this template that method called the weather forecast controller and the get endpoint on this so here there is a bunch of random data getting generated which is why we saw the weather data respond the filter we added under the startup.cs using the options.filters is specified at a global level this means this filter is applied to any endpoint under this application to create a new controller let's head off into the weather forecast controller copy this and duplicate it right on top so let's call this as user controller because this could be the data that is getting returned for a specific user so let's name this user and add in a get method so let's say public string get and simply return a hello world now this is a simple get method which returns the hello world string before we run this application let me go to the startup.cs and turn off the swagger endpoint you can do that by going under the configure method and commenting out this code the reason why i'm doing this is because i don't want to be navigating through the swagger ui and clicking the appropriate execute buttons to run this api to change the default landing page we also can go into the properties and update the launch settings.json file so here you can see the launch url is swagger so let's make this weather forecast which is the default api endpoint let's also make sure to change the other profile which is part of this settings file so let's save and run this application to see this in action the application is running and it has directly invoked the weather forecast api and returned back the data if i navigate back into rider i can see the on action executing and the executed as before so let's switch back and also call the user endpoint which is at slash user now this returns the hello world message so switching back to rider i can see the on action executing and executed is called once more this is why this filter is currently applied at the global level any action endpoint that you execute this filter is also going to execute in that pipeline filters can also be applied specifically for a controller or even at an action method level these are usually done by using attributes so let's see how we can do that now let's stop running this let's navigate back to the my sample action filter to use this filter as an attribute we need to inherit this class from the class attribute this is the common convention in dot net programming so now this makes it possible to use this as an attribute for demo purposes let's simply take in a string parameter so that we can use this to identify where this filter attribute is getting used so let's say string name and make sure to add a backing property for this now we can start using this inside the console.writeline statements so let's use string interpolation and pass in the name inside of here so let's say on executing and passing the name similarly we can do that for this console.writeline statement as well so this is going to call on executed the name and also the on executing name normally attributes in dotnet ends with the name attribute so let's rename this class to name this as my action filter attribute and click next now this is updated all the attribute references let's navigate to the startup.cs class and comment out this global level filter now to apply this at the controller level let's navigate to the weather forecast controller and right above the class name we can apply this attribute so let's specify my sample action filter and pass in a name for this so in this case let's use controller now if you run this application this is going to again run it as before but the only difference is this is going to happen only at this controller level so the default weather forecast endpoint is executed so let's navigate back to rider and we can see the on action executing and executing getting called and it's also logging out that it's from the controller now if we switch back and execute the user endpoint this doesn't log this filter anymore because the filter is currently applied at the controller level similarly you can also apply this action filter just at the get method level so you can remove that from there and specify it here and we can specify this is at the action level now the parameter is just for demo purposes it could be anything else that's used inside your application now in this case if there are other methods inside this controller it will get invoked only for the get action method because we have applied it only at that method level the action filter that we just added is a synchronous action filter this is the reason why it has a non-action executing and also an on action executed method we can also make this into an asynchronous filter by using an i a syncaction filter interface let's see an example for that so let's go to the solution explorer and create a new class let's call this my sample async action filter now as i said we need to implement the iesync action filter interface for this case let's implement the interfaces and this now has only one method which is the on action executing sync this has two parameters which takes in the action executing context which is the context in which this is getting executed and also the next delegate now this is the next action in this pipeline that needs to get executed this is very similar to the middleware pipeline if you are familiar with it if not please check out the video link here to understand more about middleware and how that request pipeline works to implement this attribute very similar to the other one let's take in the constructor take in the name use this as a field and we can now wrap around this next delegate execution now inside the implementation we can call the next method which will automatically invoke the next filter in this pipeline so let's call away and specify next so this is going to call the next action method let's make sure to specify the sync on this method because there is an await call to simulate the before and after the only thing we need to do now is to call that before and after executing that method so in this case right before calling the next we can specify console.writeline and say before async also make sure to pass in the name as a string interpolation so let's specify underscore name and we can call this after the await dot next call as well and name this as after sync execution if we need to use this as an attribute let's also inherit from the attribute class in here and let's make sure to name this as my sample async action filter attribute to start using this attribute let's switch to the weather forecast controller and update this to use my sync action filter let's run this to see this in action the application is running so let's switch back to rider and here we can see this is now calling the before sync execution action and the after sync execution action so as expected it's calling the before and after which is wrapping around the next call now that we have seen the asynchronous and synchronous version of the filters let's look at the order of execution of these filters until now we just had one custom filter added extra so let's start adding multiple action filters and see what happens in that case as we saw earlier if we have multiple filters they are going to get stacked inside the filter pipeline so similar to the middlewares this filters is also going to have a before and after call so each of these filter is going to wrap around each other which means the one on the top is going to wrap around the one on bottom and so on let's see this in action so switching back to our code it's easy to add multiple filters so let's simply repurpose this action filter attribute specify it at the controller level so in this case let's specify for this controller rename this as controller so we know where exactly this is getting used and also navigate back to the startup.cs class and uncomment this at the global level so we can specify global in this case now this is using the sample action filter and not the async version but both should behave the same in this pipeline with these setup let's run the application to see how this gets executed the application is running so let's switch back to rider and here we can see now there are multiple statements getting logged so as we expected initially the global scoped filter is getting called which is the on action executing part of that right after that the next action filter gets executed again the before method of it so since that is the async variant there is a before async execution console line and this specifies that it is from the controller scope since we also specified one at the action scope the before sync execution for the action is getting executed right after this point we have the action code getting executed in this case it returns the weather forecast responses after that on the way back it starts executing the after part of the action filters so here we have the after of the action getting executed first because that's what it sees on its way back as the first filter attribute right after that it calls the execution from the controller and ends with the global level so you can see each of these scopes wraps around the one that's below it the default order in this case is that the global gets executed first on the way down and it gets executed last on the way up regardless of whether it's an asynchronous attribute or a synchronous attribute it follows the same pipeline we can override this default order of execution by implementing another interface so let's go to the sample action filter which is the synchronous version of the filter and implement the i ordered filter interface now this has one property which is the order so we can specify the order of execution by specifying this in order property so let's make this as a set variable and set this again from the constructor so let's pass in the order that we want so let's say order by default the order is always getting set to 0. so let's make this a default variable with 0 as the value so let's set order and specify the order from the constructor let's navigate back to startup.cs and we can optionally update this order if we want now if you don't do anything it's going to maintain the same order as before lower the value of this order the higher the execution it gets so if this is a negative number then that's going to get executed first so in this case since by default 0 is applied for all orders if we want to make this the last let's give this a positive value so if we update this and specify as one then this is going to get executed last so let's run this the application is running so let's switch back to rider now here we can see the first filter that gets executed is the one from the controller followed by the action since we overwrote the order for the global attribute and gave it as 1 this is getting executed last so remember the lesser the value the higher it becomes in the filter chain so if this is a negative number in that case global would have got executed first so right after executing the two global it continues back with the action and then the controller again let's stop this and see another example with a negative number let's remove this one specify it as default so that it executes in the default request scope let's navigate to the weather forecast controller instead of the sync variation let's use the synchronous variation because that's where i have specified the order and pass in a negative value here so let's specify minus 10 and now this is going to execute it as the first filter so let's run this and see this in action the endpoint is executed so let's switch back to rider and here we can see the on action executing of the action getting called first this is because we had specified a minus 10 as the value of the order so the lesser the number the higher it gets in the chain of execution so right after executing action it follows the default scope order because all the other filters have a value of 0 for their order so then it executes global and then controller and on the way back it again calls the controller global and finally it calls the action which is wrapping around at the highest level if two filters have the same order then the scope is used to determine which one comes first that is what we see the controller and the global getting executed in the same order as we expect because both of them have the value 0. i hope this helps you to understand about filters in asp.net core how to create a custom filter and how to set up inside the request pipeline i will do a follow-up video on filters showing how to use dependency injection and also the inbuilt filters that is there as part of asp.net core so make sure to hit that subscribe button if you want to be notified if you have any comments or questions please feel free to drop in the comments below i will make sure to reply to each one of you thank you and see you soon
Info
Channel: Rahul Nath
Views: 4,902
Rating: 4.9649124 out of 5
Keywords: asp.net core web api, aspnet core filters, filters in asp.net core web api, filter pipeline in asp.net core, filter pipeline, how filter works in asp.net core
Id: mKM6FbxMGI8
Channel Id: undefined
Length: 18min 23sec (1103 seconds)
Published: Wed May 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.