Types Of Filters In MVC

type
Authorization filters :

  • It is used to implement authentication and authorization for controller actions.
  • Executed before action filters and exception filters.
  • Use IAuthorizationFilter interface.

Let us see an example of how to implement Authorized filter on our actions.

Step 1:


Add your own AuthorizedController named MyAuthorizedController in Controllers folder as in the following figure.

controller

Step 2:

Inherit FilterAttribute class and IAuthorizationFilter interface for your MyAuthorizedController as in the following figure:

MyAuthorizedController

Step 3:

Now implement OnAuthorization method. Write your authentication logic here; also you can do role based authentication by this controller.

code

Step 4:

In this example, I am passing data in the session and printing it on the page to show proper functioning on authorized filter. The code is shown in the figure below.

code

Step 5: Now come to HomeController and implement MyAuthorized attribute here, shown in the following figure.

HomeController

Then go to your Index page and Access Mydata Session here, just to confirm whether OnAuthorization
Action executes properly or not.

Execute

Step 6: Let us run the project and you can see the following output:

result