Here you learn different type of filters in asp.net MVC, what are action filters, how filters are used in asp.net mvc application development with real-time examples.
Action filters are the filter we put as attribute on action result, commonly known action filters are HandleError, Authorize, OutputCache.
public class mvcController : Controller { [HandleError] public ActionResult filters() { return View(); } }
In general terms filters are some mechanism that helps to verify any action, in Asp.net MVC there are some such filters, filters are basically custom classes that provide a way to check pre-action and post-action behavior of any action methods in controller
Remember, action verbs and action filters are different, through there are very similar in nature, we can create custom action filter, but cannot create custom action verbs [HttpGet, HttpPost, HttpDelete]
.
Filters are executed before or after any action, we simply can apply filters on any controller or on any action.
For example, Authorize filters can be applied on any action where you want to make sure that the request has come from an authorized person or HandleError filter can be applied on any action or any controller.
Let's look at some examplepublic class mvcController : Controller { [HandleError] public ActionResult filters() { return View(); } }
public class mvcController : Controller { [Authorize] public ActionResult filters() { return View(); } }
public class mvcController : Controller { [OutputCache(Duration = 50)] public ActionResult filters() { return View(); } }
In all above example we have applied filter on Action, same way you also can apply filter on any controller.
You also can create your own customize filter class inherited from ActionFilterAttribute
or any other class which is finally inherited from FilterAttribute
class.
internal class MyCustomFilter : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { var response = filterContext.HttpContext.Response; // do whatever you want to do with request object } }
Once your custom filter is ready, same way you can apply on any action or any controller in your application
You may look at how a custom compress filter can be written