.NET 8 💥 - ASP.NET Core Web API Filters
Summary
TLDRThis video tutorial by Muhammad explains how to utilize filters in a .NET API. It covers the flow of HTTP requests through middleware before reaching controllers and actions, and how filters can be added to manage these actions. Muhammad demonstrates creating and implementing both synchronous and asynchronous filters, customizing their execution for specific actions. The tutorial also shows how to combine multiple filters and control their order of execution, offering a comprehensive guide to enhancing web API functionality with filters.
Takeaways
- 😀 The video discusses the utilization of filters within a .NET API to manage and control actions more effectively.
- 🔧 Filters in .NET API can be used to add an extra layer of functionality such as logging, auditing, and validation before and after action execution.
- 🛠 Middleware and filters work together, with middleware processing requests first and filters providing additional control over specific actions.
- 📝 Middleware is essential for every request, whereas filters can be selectively applied to certain actions or controllers.
- 📌 Filters can be implemented to run either synchronously or asynchronously, offering flexibility in handling requests.
- 📝 The script provides a step-by-step guide on creating custom filters by implementing the IActionFilter interface.
- 🔑 Filters can be attached to actions using attributes, allowing for the specification of action-specific filters.
- 🔄 The order of filter execution can be controlled, allowing for a structured approach to processing requests.
- 📊 The video demonstrates how to implement and test filters using a practical example with a Drivers controller.
- ⚙️ Filters can be used to execute code before and after an action, providing a way to log or modify the request and response as needed.
- 🔍 The script concludes by showing how to combine synchronous and asynchronous filters for a single action to achieve desired outcomes.
Q & A
What is the main topic of the video?
-The main topic of the video is utilizing filters within a .NET API, explaining how they work, and how to implement them in code.
What is the normal flow of a request in a web API?
-The normal flow of a request in a web API involves the request going to the API, finding the controller and action, executing the action, and then returning a response.
What are middlewares in the context of web APIs?
-Middlewares are layers that a request has to go through before it hits the controller. They can handle tasks such as authentication, authorization, verification, and logging.
What is the purpose of filters in a .NET API?
-Filters in a .NET API provide an extra layer of control over actions. They allow developers to run code before and after an action's execution, giving more control over the request handling process.
How can filters be applied in a .NET API?
-Filters can be applied globally to all actions, or specifically to certain actions or controllers, by attaching them in the code.
What is the difference between middleware and filters in terms of execution order?
-Middlewares always run first for every request, while filters can be specified for individual actions and run before and after the action's execution.
Can filters be applied to only specific actions rather than all?
-Yes, filters can be applied to specific actions or controllers, allowing for more granular control over which requests are processed by the filters.
How can multiple filters be ordered in a .NET API?
-Multiple filters can be ordered by specifying their execution sequence in the code, determining which filter runs before or after another.
What is an example of a filter implementation in the video?
-An example given in the video is a logging filter that outputs messages to the console before and after the action's execution.
How can asynchronous filters be implemented in a .NET API?
-Asynchronous filters can be implemented by using the async/await pattern in the filter's method, allowing the request to move through filters without blocking the execution.
What is the benefit of using both synchronous and asynchronous filters?
-Using both synchronous and asynchronous filters allows for a combination of immediate processing and non-blocking operations, providing flexibility in handling different types of requests.
Outlines
🔧 Understanding Filters in Web API
In this segment, Muhammad introduces the concept of filters within a web API, explaining their role in processing requests before they reach the controller. He outlines the typical request flow in a web API, emphasizing the importance of middleware that handles tasks like authentication and authorization. Muhammad then transitions into explaining how filters can be used to add an extra layer of control, intercepting requests and responses to perform specific actions like logging or validation. The explanation is geared towards understanding the mechanics of how filters fit into the broader architecture of web API request handling.
🛠️ Implementing Filters in Code
Muhammad demonstrates how to implement filters in a practical coding scenario. He starts by creating a new directory for filters and then a class named 'MyLogging' that implements the 'IActionFilter' interface. This interface requires implementing two methods: 'OnActionExecuting' and 'OnActionExecuted'. He uses console logging to show the filter's effect before and after action execution. The video then shows how to attach this filter globally to all actions within the 'Program.cs' file, and how to test it using Postman. The segment concludes with a discussion on how filters can be applied to specific actions rather than globally, enhancing the control over request processing.
📝 Creating and Applying Action-Specific Filters
This part of the video focuses on creating filters that can be applied to specific actions within a controller. Muhammad modifies the 'MyLogging' filter to include a constructor that accepts a color name, making it more versatile. He then shows how to use this filter as an attribute on a specific action within the 'DriversController'. The video illustrates how this filter executes only for the specified action, demonstrating the flexibility of filters in handling requests. The segment also covers the creation of an asynchronous filter, 'MyLoggingAsync', and how to apply it to an action, highlighting the difference between synchronous and asynchronous filter execution.
🔄 Combining Multiple Filters and Conclusion
Muhammad concludes the tutorial by showing how to combine multiple filters, both synchronous and asynchronous, for a single action. He modifies the 'DriversController' to include both types of filters and demonstrates their execution order. The video emphasizes the ability to control the order of filter execution, which is crucial for managing the request processing pipeline effectively. The segment wraps up with a summary of how filters provide fine-grained control over actions in a web API, allowing developers to add specific functionalities like logging, auditing, or validation. Muhammad invites viewers to ask questions in the comments and encourages support through Patreon or buying him a coffee.
Mindmap
Keywords
💡Filters
💡Middleware
💡API
💡Controller
💡Action
💡Request
💡Response
💡Authentication
💡Authorization
💡Logging
💡Asynchronous
Highlights
Introduction to utilizing filters within a .NET API to understand their functionality and implementation.
Explanation of the request flow in a web API, including the role of controllers and actions.
Discussion on middleware and its role in intercepting requests before they hit the controller.
Introduction of filters as an additional layer for managing actions in a .NET API.
Demonstration of how filters can be attached to requests and their impact on the request-response cycle.
Illustration of middleware and filters working together in a layered approach within an API.
Explanation of how filters can be applied to specific actions, controllers, or globally.
Creation of a custom filter in a .NET project and its implementation as an IActionFilter.
Example of adding a logging filter to demonstrate its usage before and after action execution.
How to attach a filter to every action in a .NET API using the program.cs configuration.
Demonstration of a filter in action using Postman to test API endpoints.
Adjusting filters to execute on a single action rather than all actions within a controller.
Creating an asynchronous filter and its implementation compared to a synchronous one.
Attaching multiple filters to a single action and controlling their execution order.
Practical example of combining synchronous and asynchronous filters in a .NET API.
Final thoughts on the importance of filters in providing more control over API actions and requests.
Closing remarks, invitation for questions, and acknowledgments for the video.
Transcripts
Hello friends thank you for watching
this video I am Muhammad and today we're
going to be discussing how we can
actually utilize filters within our. net
API we're going to be understanding how
do they work how do they fix within
middle words and then we're going to be
actually seeing how we can Implement
them within our code so let's get
started so what we're going to be doing
right now is we're going to be
understanding what's going to happen
whenever a request actually comes into
our web API so let's say we have a
request coming in and within this
request we're just going to hit a
controller and within this controller
we're going to have an action so the
request flow will going to be something
like this and then once the action
finish executing then we're going to get
back a response at the end and this flow
that we're currently seeing here is
basically the normal flow whenever we're
handling anything when it comes to a web
API we're request we're going to go to
our API it's going to find the
controller the action the actions going
to execute and response but this is not
the only way it's going to happen this
is a very simplistic view of how stuff
happen within nut we're going to have a
lot of different layers that's going to
request has to go through before it
actually even hits the controller ler so
we're going to have some like middle
Wares available in place and within
those middle words the request is going
to be basically go through different
types of either authentication
authorization uh verification Etc and
then it will hit the controllers so we
can see here that within our net there's
a lot of different middle Wares that
actually might intercept the call before
it actually execute or actually reach
the controller and all of this we have
discussed previously how actually
middleware comes into place and how do
they work in conjunction with our
controllers on action so on top of that
we're going to be discussing today how
we can actually add an extra layer in
order for us to actually manage our
actions and this is going to be
something called filters so what we want
to do is we want to actually attach a
filter to our request and through that
the filter will actually then forward
the request to response and once the
action has finished executing it's going
to basically then go to the filter and
then instead of the action directly
returning the response then through that
the response is going to go back and
this is what we're going to be doing
today we're going to be trying to adding
those filters in place and we're going
to be understanding how they actually
work so what I have here is I have a
full example of what's actually going to
happen when when the request comes in so
this is a HTTP request coming in we can
see it's going to hit the middleware So
within the middleware we're going to
execute some logic once it execute the
logic the middleware will forward that
request to the second middleware the
second middleware will also take this
request it will execute another logic so
one could be authentication the other
one could be authorization the third one
could be logging so let's add this here
so we can say this is authentication
this is authorization this could be
logging this could be background jobs I
don't know it could be something around
those lines ex start executing an in
appro and acing background operation and
lastly for example here so we're going
to have authentication authorization
logging and the background jobs and
basically we can see here that the
request flow is going to go from
middleware one once it execute the
authentication it will be forwarded to
middleware 2 execute the authorization
forwarded to middleware 3 execute the
author the loging forward it to
middleware 4 execute the background
shops and then here we want to actually
start executing the request when
actually it hits the controller so here
it's going to be the controller so once
it actually hits the controller what do
we want to do we want to actually run
some code before it actually hits the
action which is going to be executing
and this is what we're going to be doing
we're going to be actually seeing how we
can build those layers here filters and
these filters here is going to allow us
to actually have much more control about
those requests so we can have filters
here for specific types of auditing we
can have filters here for specific types
of uh logging mechanism we can have
specific types of validation that we
want to add so there's L different
implementation that we can actually
execute on on these different types of
filters that we want want to add soil
filters here will play a cual role into
the actual action itself so all of these
different middlewares that we have
before these will be executed for every
single request coming in there is no way
around it it will going to be so let's
say we have an an API with 100 end
points all of these 100 end points are
going to go through in this example
through these four different middlewares
on the other hand for filters we can
specify for every single action its own
filters so if we specify a filter that's
going to run on only five actions only
these five actions will actually have
these filters enabl onto them so filters
can be on the controllers and they could
be as well on the action itself so we're
not only limiting it to an an action
it's going to be for all request filters
for specific actions or controllers and
this is going to be the main thing so
we're going to be able to have a much
more control about what action is going
to be executed for which type of request
coming in and basically as we once we
the request will hit the controller if
we have a a filter on the action itself
so once that request hits the controller
the controller then will forward the
request to the filter on that action we
execute the filter before the execution
of the action then the action is
executed and then once that execution
has finished execution then we're going
to run the code after it uh from the
filter side once that's done then we're
going to be propagating and popping back
the response up into the same layer to
the same middleware so it's going to go
through the background jobs then it's
going to go to the logging to the
authorization authentication and then
we're going to get back the response so
all of this flow that we currently be
seeing here is going to be basically
building on top of the each other so
it's going to go through first second
three four middle Wares and once it's
going to go through those four middle
Wares it's going to go to the action
once the action does its work the filter
is going to be on the executing there as
well before and after and then we're
going to be returning back the response
so we can think this as a layered cake
and this within this layer cake the
filter is going to be sitting all the
way on top and the uh middle Wares are
basically going to be supporting this so
as we can see here that this is also
going to run a in a very structured
approach so the middlewares always have
to run first and then we're going to
have to run the filters when it comes to
filters we can have for example within a
single action we can have different
filters so we can have two three four
filters and we can actually specify the
order so so in this example here we have
added another filter so we have filter
one here run before then we're going to
go to filter two then once it have run
then we're going to go to the execution
then it's going to go to filter two then
to filter one and the nice thing about
if we're going to add multiple filters
filters together we can actually add
ordering to them so we can say this is
going to run before this or this going
to run before for this and we're going
to be seeing how we can actually
Implement something similar to this so
now that how we have understood how
filters and middleware works together
let's jump into our code and see how we
can Implement something like that so in
this example here we have the same
project that we have always been working
on where we have a controller we have a
driver's controller and we have an
achievement controller we're basically
doing a different crubs operation on our
controllers here so we can add a driver
remove a driver delete a driver and add
all of them we're using a SQL light
database and if we go to the program.cs
we can see here that we barely have any
middleware so we have basically the htps
redirection middleware we have the
authorization middleware and the map
controllers middleware so these are the
middlewares that we currently have don't
really have any other middlewares
running into place so what we want to do
right now is we want to create our own
filter and then once we create our own
filter we're going to attach it to one
of these controllers actions and then
from there we're going to be seeing how
that will work so what I want to do here
in the root directory I'm going to
create a new directory and I'm I'm going
to call this directory filters I can
call it whatever I want perfect so now
that I have created filters I'm going to
add a new class and this class we're
going to name it my logging okay great
so now that my class is up and running
what I want to do is I want to inherit
or basically I want to implement an
interface called I action filter and as
you can see here it's asking me directly
to implement one of the methods so I'm
going to implement this meth method and
click okay and it's going to ask me for
Implement another one okay perfect so
now that I have implemented both methods
we can see here that difficult
implementation that I need to do which
is going to be on action executing and
on action executed so the first thing
that I want to do to make it as simple
as possible is directly output stuff
onto the console so console do right
line we're going to say this filter
executed before I'm going to copy this
put it here I'm going to say here filter
executed after so now that I have done
this I now created my first filter and
then basically I attached the action to
it once I have done this I want to
basically go to my program.cs and what I
want to do is I want to attach it now
just so we can see it works to every
single action that currently exists so
in order for me to do that on the
Builder do service of add controller I
want to configure it to actually utilize
this filter so I'm going to put options
options do filters do add and I'm going
to say new my loging pretty
straightforward so now if I want to run
this so now that my application is
running let's go to postman and within
Postman I'm going to get all the drivers
and now we should be able to see that I
got one driver that currently exist and
if I go back to the log we can see here
I have filter executed before and I have
filter executed after and we can see
inside this is my command to the
database to execute the to extract the
driver's information so we can see here
now that directly my filter is actually
running whenever I execute any command
so if I try to run this again multiple
times you should be able to see that
this is directly after the execution
filter executed before executing again
then executing after similar executed
before then executed after so we can see
that this is working as it should be
let's try different endpoint so let's
say I want to get driver ID specify the
driver send we can see I'm getting a
single driver here again for this as
well I'm getting executed before and
we're getting here as well filter
executed after so this is all fine and
uh good but filters as we said we have
the power to actually specify them into
a single action rather than executing
them on all actions and controllers so
let's see how we can actually only
execute this on a single action so I'm
going to command this out and I'm going
to go to my loging here and I'm going to
update this to actually be able to
specify it and to make it as an
attribute available so the first thing
that I want to do is I want to put here
attribute and now once I put an
attribute here it means that I'm
actually able to make it as an attribute
and I want to update this in order for
me to take advantage of that so first of
all what I want to do is I'm going to
put private read only string and I'm
going to specify something called a
Coler name and I'm going to initialize
this through the Constructor okay
perfect and now once I have done that
what I want to do here is I want to
actually specify the Coler name so I'm
going to put here string interpolation
and I'm going to specify here that I'm
going to use the Coler name similarly
I'm going to do the same thing here and
now that I've done this I'm going to go
to my driers controller and for the get
old drivers which is the one that we
have used before can add a filter here
and this filter is going to be my
logging and for this we're going to give
it a name or basically the Coler name
that we currently specified here and for
this I'm just going to call it all
drivers so let's run this and see how
actually going to execute so now this is
running I'm going to go back to postman
and if I run this right now we can see
here this is with an ID I should not be
able to see that so now this is running
I got my response back if we go back to
postman we can see here that I did not
get that that logging inside my console
so now if I remove this and I'm now
doing get all driers I click on send we
get all drivers here and we can see here
that I got the filter only executed on
this so we can see filter executed
before all drivers and filter executed
after all drivers so we can see here
that this filter only executed on one
single action rather than having it
executed on all different actions so if
I try to put this back here the driver
ID that I have and I try to put it here
and click on send we can see I got back
the response but here we can see the
filter did not execute okay perfect so
now that I have was able to create the
filter only on single action and I was
able to actually pass information to my
filter for me to be able to utilize it
let's see how we can actually have a
filter which is going to be async so
here if I go to my logging filter that I
created let me stop my application we
can see here that everything is running
in a synchronous matter if I want to
execute an async one so I'm going to
create a new class I'm going to call it
my logging async and then here what I
want to do is I'm going to add it as an
attribute as I did before but the one
difference that I want to do here is I'm
going to put I a action filter and once
I have added this it's going to ask me
to actually implement the member and we
can see here instead of having two uh
members which is on on action executing
and on action executed I have one single
member and let me just put this so you
can see it on a single line but then the
asynchronous one I get only one method
and this method is contain a context and
contain an next so here what I need to
do is in order for me to make this
functional I need to put away next I
need to make this as an async and now
basically what I'm doing here is if we
go back to my diagram I'm actually
allowing this to run in a similar manner
to this where I'm having the next object
object in order for me to move it from
one to another I'm utilizing this
asynchronous approach in order for me to
allow the movement of the request from
one filter to another so if I do here
like this console do right line I'm
going to put this before the before the
request goes execute and we're going to
put after the request execute and I'm
going to do the same thing as I done
here I'm just going to copy this so I'm
actually able to have a reference to
Who's Calling it and I'm going to attach
this here and I'm going to put here it's
going to be Caller Name make this as an
synchron as string interpolation
similarly here perfect so now that I
have done this let's see how we can
actually utilize this my loging async
I'm going to copy this action I'm going
to copy the name of my class go to my
controllers and I'm going to add this
only when getting a single driver so I'm
going to go here to set get a single
driver I'm going to add this here and
then I'm going to specify my color name
and I'm going to say this color name
it's going to be get single driver so
now if I execute this we can see it's
running if I go back to postman now if I
get this run this this we're going to
get Lewis perfect if I go back to Rider
we can see here that before the request
execute get single driver and then after
the request execute G single driver this
is an async filter here we can see the
other one did not come into place if I
remove the ID here in order for me to be
able to get all the drivers and click on
send we'll be able to see I get my
synchronous approach which is going to
be filter executed before all drivers
and filter executed after all drivers
compared to the one before that which is
after the request executed so which is
going to be async or not let just make
the text a bit more clearer so I'm going
to put here sync so we know the
difference and here sync as well here
I'm going to put a sync and I'm going to
put here a sync okay perfect so let us
run this again get all drivers so this
should be the synchronous request we can
see I have my synchronous request coming
here and my synchronous request coming
here okay perfect if I add the driver ID
click on send now if I go down I can see
my a synchronous one is running and I
have my a synchron this one is running
as well so that's great so one of the
last items that we want to cover today
is we're going to be seeing how we can
actually attach two of them together so
what I'm going to do is I'm going to
take the asynchronous one and I'm going
to add it to get all drivers so all I'm
going to do here is after all my logging
all drivers I'm just going to update
this here and I'm going to run my code
again I'm going to go back to postman
and forget all drivers let's see what's
going to happen now we got the response
pack if I go back here we can see here
that first the synchronous one has run
and then the asynchronous one has run
afterward then the asynchronous finished
executing and then the synchronous one
here so we can see within this we are
actually able to attach multiple filters
together in order for us to get the
response that we want and to get the
action that we want and if I change the
order of this so if I put first of my a
synchronous and then my synchronous I'm
going to stop this and I'm going to run
this again go back to postman execute it
cut back the response and now we can see
here that the first one has happened
which is the asynchronous one and then
the synchronous one has has executed
synchronous finished executing and the
async has executed okay perfect So
within this we were able to see how
filters can actually work in conjunction
with middle in order for us to have much
more control about our actions and
basically we're able to specify specific
actions to run on specific request
rather than having it run on all of the
single rather than having it running on
all of the incoming requests filters
allow us to provide much more control on
what types of functionalities we want to
add to controllers to actions we can
specify the orders we can have actually
synchronous and asynchronous filters
available for us with that said I hope
this video was helpful if you have any
questions please make sure you put them
on the comments down below if you have
um if you'd like to support me please
consider supporting me on patreon or
buying me a coffee with that said thank
you very much for watching and have a
great day
浏览更多相关视频
Build a Slicer Panel in Power BI Like a PRO
How to Use a TCS3200 Color Sensor with Arduino (Lesson #38)
#30 Spring Security | Custom Login
Best WooCommerce Filter Plugin? - Filter Everything FREE
MGF Working multi grade filter and Pressure Sand filter working principle and internal structure #1
Creating a Web API Project
5.0 / 5 (0 votes)