Filter's in MVC
Filters in MVC provide us with an elegant way to implement cross cutting concerns.Cross cutting concerns is the functionality that is used across our application in different layers.Common example of such functionality includes caching ,exception handling and logging.
Cross cutting concerns should be centralized in one location instead of being scattered and duplicated across the entire application.This makes updating such functionality very easy as it is centralized in one location. Filters provide this advantage as they are used to implement cross cutting concerns using a common logic that can be applied to different action methods and controllers.Filters are implemented as classes that contains code that is executed either before the action method is executed or after the action method executes. We can create global or controller filters in MVC 4.Global filters are filters that are applied to all the action methods in the applicationwhile controller filters apply to all the action methods in the controller.
We can create a global filter by creating a class and registering it as a global filter
Hide Copy Code
public class TestGlobalFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
context.RequestContext.HttpContext.Response.Write("Global filter's in MVC are cool...");
}
}
Hide Copy Code
//Register our global filter
GlobalFilters.Filters.Add(new TestGlobalFilterAttribute());
As we have registered our filter as global action filter this will automatically cause the filter to execute for any action method .Below we can see our global filter in action.
Now suppose we want one of our action method’s not to execute filter logic.In MVC 4 there is not direct way to implement this.
No comments:
Post a Comment