|
Ak filtre zavedené skôr nespĺňajú požiadavky, tento vlastný filter by sa mohol hodiť, ak chcete definovať vlastnú logiku spracovania pred a po vykonaní a vrátení metódy správania. Na prispôsobenie filtra zdedíte triedu ActionFilterAttribut, čo je abstraktná trieda implementujúca rozhrania IActionFilter a IResultFilter, hlavne prepísaním štyroch virtuálnych metód na dosiahnutie injekčnej logiky pred a po vykonaní a návrate metódy správania metóda | parameter | popis | OnActionExecuting | ActionExecutingContext | Vykonajte pred vykonaním behaviorálnej metódy | OnActionExecuted | AkciaVykonanýKontext | Vykonať po vykonaní behaviorálnej metódy | OnResultExecuting | VýsledokVykonanieKontextu | Spustiť pred návratom metódy správania | OnResultExecuted | VýsledokVykonanýKontext | Spustiť po návrate metódy správania |
Štyri metódy sa vykonávajú v poradí OnActionExecuting>OnActionExecuted>OnResultExecuting>OnResultExecuted. Argumenty vyššie uvedených štyroch metód sú zdedené z triedy ContollorContext. Napríklad nižšie je definovaný vlastný filter
- 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;
- }
- }
Kopírovať kód
Behaviorálne metódy jeho použitia sú definované nižšie - [MyCustomerFilter]
- public ActionResult CustomerFilterTest()
- {
- Response.Write("<br/>Invking CustomerFilterTest Action");
- return View();
- }
Kopírovať kód
|