Asp .Net MVC - SPLessons

ASP.Net MVC Filters

Home > Lesson > Chapter 18
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

ASP.Net MVC Filters

ASP.Net MVC Filters

shape Description

Filters are the Custom Classes that provide both declarative and programmatic means to add PreAction and Post Action behaviors to the controller action methods.

When to use Filters?

shape Description

In ASP.Net MVC controllers will define Action Methods, that usually have a one to one relationship with possible user interactions within a view page. When the user sends the request to any Action Method, then it will run and will send the result to the respective view. In such cases and in some scenarios, one can like to execute some kind of logic code, before the action method and after the action method to use the filters.

shape Types

ASP.Net MVC supports 4 types of filters.
  • Authorized Filters
  • Action Filters
  • Result Filters
  • Exception Filters

Authorized Filters

shape Description

Authorized Filters are inherited from the IAuthorization Filter Interface. These are used to make the Security Decision about.
  • Whether the method should be executed or not.
  • Permission should be given to the controller class or not.

Action Filters

shape Description

Action Filters are inherited from the IAction Filter Interface. This interface provides following Action Methods.
  • OnActionExecuting()
  • OnActionExecuted()
OnActionExecuting() OnActionExecuting() method will run Before the execution of the Action Method. If we want to run any code before the execution. Then, we will write the code in this method. OnActionExecuted() OnActionExecuted() method will run After the execution of the Action Method. If we want to run any code after the execution. Then, we will write the code in this method. We can also use this method for any additional processing like
  • Providing Extra Data to the Action method.
  • Inspecting the return value.

Result Filters

shape Description

Result Filters are inherited from the IAction Filter Interface. This interface provides the  following Action Methods.
  • OnResultExecuting()
  • OnResultExecuted()
OnResultExecuting() OnResultExecuting() method is used to run before the Action Result object is executed. OnResultExecuted() OnResultExecuted() method is used to run after the Action Result object is executed. This method is also used to perform any additional processing of the result like modifying the HTTP Response.etc

Exception Filters

shape Description

Exception Filters are inherited from the IException Filter interface. These are especially used to handle the exception, which are unhandled during the execution of ASP.Net MVC Pipeline. Exception Filters can be used for the task like Login or displaying error page.etc.

Predefined Filters in ASP.Net MVC

shape Description

Following are the predefined filters in ASP.Net MVC.
  • Output Cache
  • Handle Error
  • Authorize
  • Validate Input
  • Validate Anti Forgery Token
All the above are known as Attribute Classes.

Attribute Filter: Output Cache

shape Description

This attribute class or filter is used to implement the cache, with the particular action method or view page. Named Parameters with Output Cache
  • CacheProfile
  • Duration
  • Location
  • NoStore
  • Order
  • SqlDependency
  • VaryByContextEncoding
  • VaryByCustom
  • VaryByParam

Attribute Filter: HandleError

shape Description

This Action Filter or Attribute class is used to handle the exception that are thrown by unhandling within the Action Method. Named Parameters with Handle Error
  • ExceptionType
  • Master
  • Order
  • View

Attribute Filter: Authorize

shape Description

This Action Filter or Attribute Class is used to implement the Security Authentication, that can be implemented by using Windows Authentication or Form Authentication or Roll Based Authentication. Named Parameters with Authorize
  • Order
  • Users
  • Rolls

Attribute Filter: ValidateInput

shape Description

This Attribute Class is used to implement the required validations for the input data. ValidateInput Filter is especially used to avoid the Injection Attacks. There are two arguments available in Validate Input as shown below.
  • Validate input(bool EnableValidation,NamedParameters).

Attribute Filter: ValidateAntiForgeryToken

shape Description

Validate Anti Forgery Token attribute class is used to avoid the cross-site postback hacking of the data. Named Parameters with Validate Anti Forgery Token Order AllowMultiple

shape Example

Example Application on OutputCache Action Filter. The outputCache Action Filter is used to implement the cache for the view page. Follow the below steps to work with the OutputCache Action Filter.

shape Step 1

Create a new MVC Application with the name FilterExample. And Create an view page with the name Example and write the following code in the Example.cshtml. [html] @{ ViewBag.Title = "Example"; } <h2>Example for ValidateInput</h2> <div> @using(Html.BeginForm()) { @ViewData["message"] <table> <tr> <td>@Html.Label("Enter any Data")</td> <td>@Html.TextBox("T1")</td> </tr> <tr> <td><input Type="submit" Value="Submit" id="Submit" /></td> </tr> </table> } </div> [/html]

shape Step 2

Create a Controller with the name Home and write the following code in the HomeController.cs. [csharp] public ActionResult Example() { return View(); } [HttpPost] [OutputCache(Duration=60)] public ActionResult Example(string T1) { @ViewData["message"] = DateTime.Now;//pass the date and time to the view return View(); } [/csharp]

shape Step 3

Run the Application and check the cache based on the data changes in the TextBox. The output is as shown below.

Example Application on ValidateInput Filter.

shape Step 1

Edit the HomeController.cs code as follows. [csharp] public ActionResult Example() { return View(); } [HttpPost] [OutputCache(Duration=60)] public ActionResult Example(string T1) { @ViewData["message"] = "Value is:" + T1;//Prints the value of Textbox return View(); } [/csharp]

shape Step 2

Run the Application to get an output and enter any HTML or ASP.Net Tags in the TextBox as shown below.

shape Step 3

Then, one will get the error as shown below.