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


    功能: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);
            }
  • 相关阅读:
    【转载自酷壳】编程能力与编程年龄
    xcode中的nslog数据格式
    xcode 的 pch 预编译头文件
    获取App的Documents路径
    使用gdb调试app
    收集的一些OC知识点
    收集到的几篇看雪学院文章
    【转】iOS平台的应用程序调试与分析
    前端技术开发的一些建议
    UIImage的两种加载方式
  • 原文地址:https://www.cnblogs.com/fanglorry/p/4498179.html
Copyright © 2020-2023  润新知