How To Implement Filters In Application Level In Mvc
ASP.NET MVC - Filters
In ASP.Net MVC, controllers define activeness methods that commonly take a one-to-one human relationship with possible user interactions, merely sometimes you want to perform logic either before an action method is called or after an action method runs.
To back up this, ASP.Cyberspace MVC provides filters. Filters are custom classes that provide both a declarative and programmatic means to add together pre-activity and post-action behavior to controller activity methods.
Action Filters
An activity filter is an attribute that you lot can apply to a controller action or an unabridged controller that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters −
-
OutputCache − Caches the output of a controller action for a specified corporeality of time.
-
HandleError − Handles errors raised when a controller action is executed.
-
Authorize − Enables you to restrict access to a detail user or office.
Types of Filters
The ASP.Net MVC framework supports four different types of filters −
-
Dominance Filters − Implements the IAuthorizationFilter attribute.
-
Action Filters − Implements the IActionFilter attribute.
-
Result Filters − Implements the IResultFilter attribute.
-
Exception Filters − Implements the IExceptionFilter attribute.
Filters are executed in the order listed in a higher place. For instance, authorization filters are e'er executed earlier action filters and exception filters are ever executed after every other type of filter.
Authorization filters are used to implement authentication and dominance for controller deportment. For case, the Authorize filter is an example of an Authorization filter.
Let'southward take a wait at a simple example past creating a new ASP.Net MVC project.
Step ane − Open up the Visual Studio and click File → New → Project carte option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Spider web.
Pace 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter project name MVCFiltersDemo in the Name field and click ok to go along and y'all will see the following dialog which asks you to set the initial content for the ASP.Net project.
Stride v − To proceed things uncomplicated, select the Empty option and cheque the MVC checkbox in the 'Add together folders and cadre references for' department and click Ok.
It will create a basic MVC project with minimal predefined content.
Step 6 − To add a controller, correct-click on the controller folder in the solution explorer and select Add → Controller.
Information technology volition brandish the Add together Scaffold dialog.
Step seven − Select the MVC v Controller – Empty option and click 'Add together' push button.
The Add Controller dialog will announced.
Step 8 − Set the name to HomeController and click 'Add together' button.
You will see a new C# file 'HomeController.cs' in the Controllers folder, which is open for editing in Visual Studio likewise.
Utilize Action Filter
An activeness filter can be practical to either an individual controller action or an unabridged controller. For example, an activity filter OutputCache is applied to an action named Alphabetize() that returns the string. This filter causes the value returned by the activity to be cached for fifteen seconds.
To make this a working example, permit'southward modify the controller course by irresolute the action method called Alphabetize using the following lawmaking.
using System; using Arrangement.Collections.Generic; using Organization.Linq; using System.Spider web; using System.Spider web.Mvc; namespace MVCFiltersDemo.Controllers { public form HomeController : Controller{ // GET: Dwelling house [OutputCache(Duration = 15)] public cord Index(){ return "This is ASP.Cyberspace MVC Filters Tutorial"; } } }
When you run this awarding, you will come across that the browser is displaying the result of the Alphabetize activity method.
Permit'due south add another activity method, which will brandish the current time.
namespace MVCFiltersDemo.Controllers{ public class HomeController : Controller{ // GET: Domicile [OutputCache(Duration = 15)] public string Alphabetize(){ return "This is ASP.Net MVC Filters Tutorial"; } [OutputCache(Duration = 20)] public string GetCurrentTime(){ return DateTime.Now.ToString("T"); } } }
Asking for the following URL, http://localhost:62833/Home/GetCurrentTime, and you will receive the following output.
If you refresh the browser, yous will see the same time because the action is buried for 20 seconds. It will exist updated when y'all refresh information technology after 20 seconds.
Custom Filters
To create your own custom filter, ASP.Net MVC framework provides a base class which is known every bit ActionFilterAttribute. This form implements both IActionFilter and IResultFilter interfaces and both are derived from the Filter form.
Let'southward take a await at a uncomplicated example of custom filter past creating a new binder in your projection with ActionFilters. Add 1 course for which correct-click on ActionFilters folder and select Add together → Class.
Enter 'MyLogActionFilter' in the proper name field and click 'Add' button.
This class will be derived from the ActionFilterAttribute, which is a base course and overrides the following method. Post-obit is the complete implementation of MyLogActionFilter.
using System; using Arrangement.Collections.Generic; using System.Diagnostics; using System.Linq; using Organization.Spider web; using System.Spider web.Mvc; using System.Web.Routing; namespace MVCFiltersDemo.ActionFilters { public form MyLogActionFilter : ActionFilterAttribute{ public override void OnActionExecuting(ActionExecutingContext filterContext){ Log("OnActionExecuting", filterContext.RouteData); } public override void OnActionExecuted(ActionExecutedContext filterContext){ Log("OnActionExecuted", filterContext.RouteData); } public override void OnResultExecuting(ResultExecutingContext filterContext){ Log("OnResultExecuting", filterContext.RouteData); } public override void OnResultExecuted(ResultExecutedContext filterContext){ Log("OnResultExecuted", filterContext.RouteData); } private void Log(string methodName, RouteData routeData){ var controllerName = routeData.Values["controller"]; var actionName = routeData.Values["action"]; var message = Cord.Format( "{0} controller:{i} action:{2}", methodName, controllerName, actionName); Debug.WriteLine(message, "Action Filter Log"); } } }
Let u.s.a. now apply the log filter to the HomeController using the following code.
using MVCFiltersDemo.ActionFilters; using Arrangement; using System.Collections.Generic; using Arrangement.Linq; using System.Web; using System.Web.Mvc; namespace MVCFiltersDemo.Controllers { [MyLogActionFilter] public class HomeController : Controller{ // Become: Domicile [OutputCache(Elapsing = x)] public string Alphabetize(){ render "This is ASP.Cyberspace MVC Filters Tutorial"; } [OutputCache(Duration = x)] public cord GetCurrentTime(){ return DateTime.At present.ToString("T"); } } }
Run the awarding and then observe the output window.
As seen in the to a higher place screenshot, the stages of processing the activeness are logged to the Visual Studio output window.
Useful Video Courses
Video
Video
Video
Video
Video
Video
How To Implement Filters In Application Level In Mvc,
Source: https://www.tutorialspoint.com/asp.net_mvc/asp.net_mvc_filters.htm
Posted by: fieldsbespoormsed.blogspot.com
0 Response to "How To Implement Filters In Application Level In Mvc"
Post a Comment