can anyone explain me with simple example what fiters are in .net
Loading
can anyone explain me with simple example what fiters are in .net
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jaimin ShethiyaPosted Apr 15, 2024, 1:26 PM
Hello Abhishek,
Please refer the below link for filters in .Net
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-8.0
https://www.c-sharpcorner.com/article/filters-in-Asp-Net-mvc-5-0-part-twelve/
https://www.c-sharpcorner.com/article/filters-in-Asp-Net-mvc-5-0-part-twelve/
https://medium.com/c-sharp-progarmming/exploring-the-power-of-filters-in-asp-net-a-comprehensive-guide-85801a7a7b1b
https://dotnettutorials.net/lesson/filters-in-mvc/
Thanks
Mithilesh TataPosted Apr 15, 2024, 6:17 AM
In .NET, filters are mechanisms that allow you to intercept and handle certain events or actions that occur within your application. They are commonly used in ASP.NET MVC and ASP.NET Core applications for tasks such as logging, authentication, authorization, and exception handling.
Let's take an example of an authentication filter in ASP.NET Core:
In this example,
CustomAuthenticationFilteris a custom authentication filter that implements theIAuthorizationFilterinterface. This interface requires the implementation of theOnAuthorizationmethod, which gets called when authorization is required for a particular action in your application.Inside the
OnAuthorizationmethod, we check if the user is authenticated. If not, we log the unauthorized access attempt using an injected logger and return anUnauthorizedResult, which can redirect the user to a login page or return an unauthorized status code.You can then apply this filter to your controllers or controller actions using attributes. For example:
This will apply the
CustomAuthenticationFilterto all actions within theMyControllerclass.Filters in .NET provide a powerful way to implement cross-cutting concerns in your application, allowing you to encapsulate common behavior and apply it uniformly across your controllers or actions.