|
In case the filters introduced earlier don't meet the requirements, this custom filter should come in handy if you want to define your own processing logic before and after the behavior method is executed and returned. To customize a filter, you inherit the ActionFilterAttribute class, which is an abstract class that implements the IActionFilter and IResultFilter interfaces, mainly by rewriting the four virtual methods to achieve injection logic before and after the execution and return of the behavior method method | parameter | description | OnActionExecuting | ActionExecutingContext | Execute before the behavioral method is executed | OnActionExecuted | ActionExecutedContext | Execute after the behavioral method is executed | OnResultExecuting | ResultExecutingContext | Execute before the behavior method returns | OnResultExecuted | ResultExecutedContext | Execute after the behavior method is returned |
The four methods are executed in the order of OnActionExecuting>OnActionExecuted>OnResultExecuting>OnResultExecuted. The arguments of the above four methods are inherited from the ContollorContext class. For example, a custom filter is defined below
- public class MyCustomerFilterAttribute : ActionFilterAttribute
- {
- public string Message { get; set; }
- public override void OnActionExecuted(ActionExecutedContext filterContext)
- {
- base.OnActionExecuted(filterContext);
- filterContext.HttpContext.Response.Write(string.Format( "<br/> {0} Action finish Execute.....",Message));
- }
- public override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- CheckMessage(filterContext);
- filterContext.HttpContext.Response.Write(string.Format("<br/> {0} Action start Execute.....", Message));
- base.OnActionExecuting(filterContext);
- }
- public override void OnResultExecuted(ResultExecutedContext filterContext)
- {
- filterContext.HttpContext.Response.Write(string.Format("<br/> {0} Action finish Result.....", Message));
- base.OnResultExecuted(filterContext);
- }
- public override void OnResultExecuting(ResultExecutingContext filterContext)
- {
- filterContext.HttpContext.Response.Write(string.Format("<br/> {0} Action start Execute.....", Message));
- base.OnResultExecuting(filterContext);
- }
- private void CheckMessage(ActionExecutingContext filterContext)
- {
- if(string.IsNullOrEmpty( Message)||string.IsNullOrWhiteSpace(Message))
- Message = filterContext.Controller.GetType().Name + "'s " + filterContext.ActionDescrip{过滤}tor.ActionName;
- }
- }
Copy code
The behavioral methods for using it are defined below - [MyCustomerFilter]
- public ActionResult CustomerFilterTest()
- {
- Response.Write("<br/>Invking CustomerFilterTest Action");
- return View();
- }
Copy code
|