Filter实现AOP

1.添加一个特性attribute类

    public class CustomerControllerFilterAttribute : Attribute, IActionFilter  、、也可以实现IResourceFilter等
    {
        public void OnActionExecuting(ActionExecutingContext context) {
            Console.WriteLine($"This is {typeof(CustomerControllerFilterAttribute)} OnActionExecuting");
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            Console.WriteLine($"This is {typeof(CustomerControllerFilterAttribute)} OnActionExecuted");

        }

    }

2.在controller上添加特性

        [CustomerControllerFilter]
        public IActionResult Index()
        {
            var user = base.HttpContext.Session.GetString("CurrentUser");
            if (string.IsNullOrEmpty(user)) {
                base.HttpContext.Session.SetString("CurrentUser", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            base.ViewBag.User = base.HttpContext.Session.GetString("CurrentUser");
            return View();
        }

 

posted @ 2021-11-06 21:25  留下成长的足迹  阅读(57)  评论(0编辑  收藏  举报