In ASP.NETMVC you can use the filter function when you have the following and similar requirements
Determine whether or not a login or user right
Decision output Caching
Anti-Theft chain
Anti-Spider
Localization and internationalization settings
Implementing Dynamic Action
Filter is a declarative programming method that can only be limited to an action (or its controller) in ASP.net mvc.
The filter is inherited from the ActionFilterAttribute abstract class and can override the void OnActionExecuting (ActionExecutingContext) and
void onactionexecuted (ActionExecutedContext)
and void Onresultexecuting (ResultExecutingContext) and
void onresultexecuted (ResultExecutedContext)
OnActionExecuting is the action that is performed before the action, and onactionexecuted is the actions performed by action
And onresultexecuting is to parse actionresult before execution, onresultexecuted is parse actionresult after execution.
The filter applied to action
Let me give you an example to see the order in which it is executed.
First we build a Filter, called Testfilter.
public class TestFilter : ActionFilterAttribute
{
public override void OnActionExecuting (ActionExecutingContext filterContext)
{
filterContext.HttpContext.Session ["temp"] += "TestFilter OnActionExecuting<br/>";
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Session["temp"] += "TestFilter OnActionExecuted<br/>";
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Session["temp"] += "TestFilter OnResultExecuting<br/>";
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Session["temp"] += "TestFilter OnResultExecuted<br/>";
}
}
Then create an action:
[TestFilter]//将此Filter应用于Action
public ActionResult filteraction()
{
return View();
}