Using Filters to Attach Reusable Behaviors
Introducing the Four Basic Types of Filters
Notice that ActionFilterAttribute is the default implementation for both IActionFilter
and IResultFilter—it implements both of those interfaces. It’s meant to be totally general
purpose, so it doesn’t provide any implementation (in fact, it’s marked abstract, so you can
only use it by deriving a subclass from it). However, the other default implementations
(AuthorizeAttribute and HandleErrorAttribute) are concrete, contain useful logic, and can
be used without deriving a subclass.
To get a better understanding of these types and their relationships, examine Figure 9-6.
It shows that all filter attributes are derived from FilterAttribute, and also implement one or
more of the filter interfaces. The dark boxes represent ready-to-use concrete filters; the rest are
interfaces or abstract base classes. Later in this chapter, you’ll learn more about each built-in
filter type.
MyFilter Demo:
02 | using System.Collections.Generic; |
07 | namespace TestMvcWebApp1.ActionResultEx |
09 | public class ShowMessageAttribute:ActionFilterAttribute |
11 | public string Message { get ; set ; } |
12 | public override void OnActionExecuting(ActionExecutingContext filterContext) |
14 | filterContext.HttpContext.Response.Write( "[BeforeAction " + Message + "]" ); |
16 | public override void OnActionExecuted(ActionExecutedContext filterContext) |
18 | filterContext.HttpContext.Response.Write( "[AfterAction " + Message + "]" ); |
20 | public override void OnResultExecuting(ResultExecutingContext filterContext) |
22 | filterContext.HttpContext.Response.Write( "[BeforeResult " + Message + "]" ); |
24 | public override void OnResultExecuted(ResultExecutedContext filterContext) |
26 | filterContext.HttpContext.Response.Write( "[AfterResult " + Message + "]" ); |
使用:
02 | using System.Collections.Generic; |
06 | using TestMvcWebApp1.ActionResultEx; |
07 | using System.Data.SqlClient; |
09 | namespace TestMvcWebApp1.Controllers |
11 | public class ShowMessageDemoController : Controller |
14 | // GET: /ShowMessageDemo/ |
15 | [ShowMessage(Message = "这是我的信息A" , Order=1)] |
16 | [HandleError(View= "Problem" )] |
17 | public ActionResult Index() |
20 | SqlConnection conn = new SqlConnection(); |
23 | return Content( " 网页内容 " ); |
输出结果:
[BeforeAction 这是我的信息A][AfterAction 这是我的信息A]
[BeforeResult 这是我的信息A] 网页内容 [AfterResult 这是我的信息A]
<customErrors mode="On"></customErrors>