MVC之路随记1--Filter的应用

时间:2023-01-28 15:37:36

功能:MVC提供过滤器Filter,使开发者不用复杂的实现AOP而直接用Filter实现同样的功能.

实现:1.定义一个类实现ActionFilterAttribute,重载借口中的方法后在Controller或者Action上加上该特性即可

2.若是每个Action都要实现,则可以在全局文件中,在注册过滤器"RegisterGlobalFilters(GlobalFilters.Filters);"之前使用GlobalFilters.Filters.Add方法加入定义好的过滤对象的实现

例子:

1.先定义过滤器类

[AttributeUsage(AttributeTargets.All,AllowMultiple=true)]//此属性让他可以执行多次
public class DemoActionAttributeFileter : ActionFilterAttribute
{
public string strMsg { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Write("<script>alert('执行之前:"+strMsg+"')</script>");
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Response.Write("<script>alert('执行之后:" + strMsg + "')</script>");
base.OnActionExecuted(filterContext);
}
}

2.使用该特性

[MyMVC3Test.Filter.DemoActionAttributeFileter(strMsg = "hello")]
public class HomeController : Controller
{
[MyMVC3Test.Filter.DemoActionAttributeFileter(strMsg = "Actionhello")]
public ActionResult Index(string strHome)
{
ViewBag.Message = "欢迎使用 ASP.NET MVC----"+strHome;
ViewBag.Msg = "hehe";
return View();
}
public ActionResult About()
{
return View();
}
}

3.全局过滤器使用

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalFilters.Filters.Add(new MyMVC3Test.Filter.DemoActionAttributeFileter(){strMsg="全局"}); RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}