Read full article on the Infragistics blog

In ASP.NET MVC, Filters are used to inject logic at different levels of request processing and allow us to share logics across Controllers. For example, let’s say we want to run a security logic or a logging logic across the controller. To do so, we’ll write a filter containing those logics and enable them across all controllers. When we enable a filter across all controllers or actions, the filter enables the upcoming HTTP request.

Let us consider a scenario of Logging: for every incoming request, we need to log some data to the files on the basis of some logic. If we don’t create this logic inside a custom filter, then we will have to write logic for each controller’s action. This mechanism will lead to two problems:

  1. duplication of code; and
  2. violation of the Single Responsibility Principles; actions will now perform additional tasks of logging.

We can mitigate the problems above by putting the logging logics inside a custom action filter and applying the filter at all the controllers’ level.

Have you ever come across source code as shown in the image below? [Authorize] is an Authorization filter, and it gets executed before any HTPP request or Action method execution.  The Authorize filter is part of MVC, but if needed, we can create a custom filter too.

Read full article on the Infragistics blog

Advertisements

One thought on “How to Create a Custom Action Filter in ASP.NET MVC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s