MVC Filter过滤器(一)

1.在项目里新增一个文件夹Filter

2.在Filter文件里头新建一个MyCustomerFilterAttribute.cs的类(继承ActionFilterAttribute,引用using System.Web.Mvc;)

public class MyCustomerFilterAttribute:ActionFilterAttribute

代码:

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //1.获取请求的类名和方法
            string strController = filterContext.RouteData.Values["controller"].ToString();
            string strAction = filterContext.RouteData.Values["action"].ToString();

            //2.用另一种方式 获取请求的类名和方法名
            string strAction2 = filterContext.ActionDescriptor.ActionName;
            string strController2 = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            filterContext.HttpContext.Response.Write("控制器:" + strController + "<br/>");
            filterContext.HttpContext.Response.Write("控制器:" + strController2 + "<br/>");
            filterContext.HttpContext.Response.Write("Action:" + strAction + "<br/>");
            filterContext.HttpContext.Response.Write("Action:" + strAction2 + "<br/>");

            filterContext.HttpContext.Response.Write("Action执行前:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff") + "<br/>");

            base.OnActionExecuting(filterContext);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Write("Action执行后:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff") + "<br/>");
            base.OnActionExecuted(filterContext);
        }

        /// <summary>
        /// 加载“视图”前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Write("加载视图前执行 OnResultExecuting" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff") + "<br/>");
            base.OnResultExecuting(filterContext);
        }

        /// <summary>
        /// 加载“视图”后执行
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Write("加载视图后执行 OnResultExecuted" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff") + "<br/>");
            base.OnResultExecuted(filterContext);
        }

控制器引用

public class UserController : Controller
    {
        [MyCustomerFilter]
        public ActionResult Index()
        {
            return View();
        }
    }

效果图(运行地址:http://localhost:1499/User/Index):

 

 

目前想到:该过滤器,可以用来授权过滤和接口、方法日志记录调用等处理

 

posted @ 2019-02-09 14:39  蜗牛的礼物  阅读(226)  评论(0编辑  收藏  举报