zoukankan      html  css  js  c++  java
  • 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);
            }
  • 相关阅读:
    向你的C语言项目中加入多线程
    <解析>speaker verification模型中的GE2E损失函数
    【笔记】 springCloud-configServer配置中心
    springboot--ActiveMQ--消息队列
    Fdfs上传的图片批量删除
    【笔记】负载均衡Robbin之不同服务使用不同的策略
    【笔记】Ribbon负载均衡伪随机算法
    【笔记】01 -- Spring-Cloud介绍
    linux防火墙
    SpringBoot起飞系列-使用idea搭建环境(二)
  • 原文地址:https://www.cnblogs.com/fanglorry/p/4498179.html
Copyright © 2011-2022 走看看