Filter in MVC

In ASP.NET MVC, controllers outline action strategies that sometimes have a matched relationship with potential user interactions, however typically you wish to perform logic either before associate degree action technique is named or once associate degree action technique runs.
To support this, ASP.NET MVC provides filters. Filters area unit custom categories that offer each a declarative and programmatic means that to feature pre-action and post-action behavior to controller action strategies.

Action Filters

An action filter is associate degree attribute that you just will apply to a controller action or a whole controller that modifies the approach during which the action is dead. The ASP.NET MVC framework includes many action filters −
• OutputCache − Caches the output of a controller action for a such as quantity of your time.
• HandleError − Handles errors raised once a controller action is dead.
• Authorize − permits you to limit access to a specific user or role.

Types of Filters

The ASP.NET MVC framework supports four differing types of filters −
• Authorization Filters − Implements the IAuthorizationFilter attribute.
• Action Filters − Implements the IActionFilter attribute.
• Result Filters − Implements the IResultFilter attribute.
• Exception Filters − Implements the IExceptionFilter attribute.
Filters area unit dead within the order listed on top of. as an example, authorization filters area unit continually dead before action filters and exception filters area unit continually dead once each alternative variety of filter.
Authorization filters area unit accustomed implement authentication and authorization for controller actions. as an example, the Authorize filter is associate degree example of associate degree Authorization filter.
Let’s take a glance at an easy example by making a replacement ASP.Net MVC project.
Step one − Open the Visual Studio and click on File → New → Project menu choice.
A new Project dialog opens.

Step two − From the left pane, choose Templates → Visual C# → internet.
Step three − within the middle pane, select ASP.NET internet Application.
Step four − Enter project name MVCFiltersDemo within the Name field and click on okay to continue and you’ll see the subsequent dialog that asks you to line the initial content for the ASP.NET project.

Step five − to stay things easy, choose the Empty choice and check the MVC checkbox within the ‘Add folders and core references for’ section and click on Ok.
It will produce a basic MVC project with nominal predefined content.
Step Six − to feature a controller, right-click on the controller folder within the resolution person and choose Add → Controller.
It will show the Add Scaffold dialog.

Step seven − choose the MVC five Controller – Empty choice and click on ‘Add’ button.
The Add Controller dialog can seem.

Step eight − Set the name to HomeController and click on ‘Add’ button.
You will see a replacement C# file ‘HomeController.cs’ within the Controllers folder, that is open for written material in Visual Studio additionally.

Apply Action Filter

An action filter may be applied to either a personal controller action or a whole controller. as an example, associate degree action filter OutputCache is applied to associate degree action named Index() that returns the string. This filter causes the worth came back by the action to be cached for fifteen seconds.
To make this a living proof, let’s modify the controller category by ever-changing the action technique known as Index victimisation the subsequent code.

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCFiltersDemo.Controllers {
public category HomeController : Controllercome "This is ASP.Net MVC Filters Tutorial";
}
}
}

When you run this application, you’ll see that the browser is displaying the results of the Index action technique.

Let’s add another action technique, which is able to show this time.

namespace MVCFiltersDemo.Controllers{
public category HomeController : Controllercome "This is ASP.Net MVC Filters Tutorial";
}

[OutputCache(Duration = 20)]
public string GetCurrentTime()come back DateTime.Now.ToString("T");
}
}
}

Request for the subsequent address, http://localhost:62833/Home/GetCurrentTime, and you’ll receive the subsequent output.

If you refresh the browser, you’ll see an equivalent time as a result of the action is cached for twenty seconds. it’ll be updated after you refresh it once twenty seconds.
Custom Filters
To create your own custom filter, ASP.NET MVC framework provides a base category that is thought as ActionFilterAttribute. This category implements each IActionFilter and IResultFilter interfaces and each area unit derived from the Filter category.
Let’s take a glance at an easy example of custom filter by making a replacement folder in your project with ActionFilters. Add one category that right-click on ActionFilters folder and choose Add → category.

Enter ‘MyLogActionFilter’ within the name field and click on ‘Add’ button.
This category are going to be derived from the ActionFilterAttribute, that could be a base category and overrides the subsequent technique. Following is that the complete implementation of MyLogActionFilter.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MVCFiltersDemo.ActionFilters {
public category MyLogActionFilter : ActionFilterAttribute ">

public override void OnActionExecuted(ActionExecutedContextfilterContext) ">

public override void OnResultExecuting(ResultExecutingContextfilterContext) ">

public override void OnResultExecuted(ResultExecutedContextfilterContext) ">

personal void Log(string methodName, RouteData routeData)volt-ampere controllerName = routeData.Values["controller"];
power unit actionName = routeData.Values["action"];

power unit message = String.Format(
" controller: action:", methodName, controllerName, actionName);

Debug.WriteLine(message, "Action Filter Log");
}
}
}

Let us currently apply the log filter to the HomeController victimisation the subsequent code.

using MVCFiltersDemo.ActionFilters;
using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCFiltersDemo.Controllers {
[MyLogActionFilter]
public category HomeController : Controller{
// GET: Home

[OutputCache(Duration = 10)]
public string Index()come back "This is ASP.Net MVC Filters Tutorial";
}

[OutputCache(Duration = 10)]
public string GetCurrentTime()come back DateTime.Now.ToString("T");
}
}
}
Run the appliance and so final output window.

Leave a Reply

Your email address will not be published. Required fields are marked *