Home > ASP.NET MVC > Filter In MVC 3

Filter In MVC 3

What is Filter

–As per MSDN “Filters are classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods.

–It let perform logic either before an action method is called or after an action method runs.” like before executing an action method of controller you want to process some business logic or some kind validation or checking upon which you determine to excute action method or not or your custome requirements

Kinds of filter in MVC 3

1) Authorization filters
2) Action filters
3) Result filters
4) Exception filters

Note : Filters run in sequence as stated above from 1 to 4

Now lets explore all of them in bit details

1) Authorization filters

–It implement IAuthorizationFilter
–It performe authentication or validate properties of the request.
–The AuthorizeAttribute class and the RequireHttpsAttribute class is example of it ,
–Authorization filters run before any other filter and used as below

public ActionResult Index()

2) Action filters

–It implement IActionFilter
–The IActionFilter interface declares two methods: OnActionExecuting and OnActionExecuted.
–OnActionExecuting runs before the action method.
–OnActionExecuted runs after the action method
–OnActionExecuted can do additional processing, like providing extra data to the action method, inspecting the return value, or canceling execution of the action method on which it is applied.

3) Result filters

–implement IResultFilter
–IResultFilter declares two methods: OnResultExecuting and OnResultExecuted
–The OutputCacheAttribute class is one example of a result filter

public ActionResult Index()

4) Exception filters

–It implement IExceptionFilter
–It execute if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline
–The HandleErrorAttribute class is one example of an exception filter.

public class HomeController : Controller

There are four way you can Create filter

–Override one or more of the controller’s On<Filter> methods.
–Create an attribute class that derives from ActionFilterAttribute and apply the attribute to a controller or an action method.
–Register a filter with the filter provider (the FilterProviders class).
–Register a global filter using the GlobalFilterCollection class.

Categories: ASP.NET MVC Tags:
  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: