Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Action Filter to set up controller variables?

I have a scenario whereby with every page request I must check the session of the presence of a particular ID. If this is found I must grab a related object from the database and make it available to the controller. If no session ID is found I need to redirect the user (session expired).

At the moment I have a custom chunk of code (couple of lines) that does this at the start of every action method within my controller - which seems like unnecessary repetition.

Is this scenario worthy of an Action Filter?

Thanks

UPDATE Some great info here guys. Thank you

like image 324
Sergio Avatar asked Jul 13 '11 13:07

Sergio


People also ask

How action filters are implemented in MVC?

Mvc. FilterAttribute class. If you want to implement a particular type of filter, then you need to create a class that inherits from the base Filter class and implements one or more of the IAuthorizationFilter , IActionFilter , IResultFilter , or IExceptionFilter interfaces.

Which filter will be executed at first using ASP.NET MVC?

as you can see from the below diagram, as soon as the controller starts execution through Action Invoker, Authentication and authorization filters are the very first filters to be triggered, followed by model binding which maps request and route data to action parameters.

Can we create custom filter in MVC?

You can create custom filter attributes by implementing an appropriate filter interface for which you want to create a custom filter and derive the FilterAttribute class to use that class as an attribute. For example, implement IExceptionFilter and the FilterAttribute class to create a custom exception filter.


1 Answers

Yes, this sounds like a good application of an action filter, as you can apply it at the controller level to operate on all actions. You could also make it part of a controller base class, if you didn't want to add it to all controllers manually, or write your own controller factory which automatically applies this action filter to each controller.

See ASP.NET MVC Pass object from Custom Action Filter to Action for passing data from an action filter to an action.

like image 117
devdigital Avatar answered Oct 07 '22 15:10

devdigital