Action过滤器
////// 执行代码前执行/// /// public override void OnActionExecuting(ActionExecutingContext filterContext){ //1.显示触发过滤器action方法的名称 string actionName = filterContext.ActionDescriptor.ActionName; filterContext.HttpContext.Response.Write("ActionName=" + actionName + ""); //2.显示触发过滤器action方法所在的控制器 string ctrlName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; filterContext.HttpContext.Response.Write("ControllerName=" + ctrlName + ""); //3.判断当前action方法是否贴有[HttpGet]特性标签 bool isTrue = filterContext.ActionDescriptor.IsDefined(typeof(HttpGetAttribute), false); filterContext.HttpContext.Response.Write("当前action是否贴有[httpGet]特性" + isTrue + ""); //4.获取当前action方法上贴有[HttpGet]特性标签的实例 object[] httpGets = filterContext.ActionDescriptor.GetCustomAttributes(typeof(HttpGetAttribute), false); foreach (object obj in httpGets) { filterContext.HttpContext.Response.Write("获取当前action方法上贴有[HttpGet]特性标签的实例:" + obj.ToString() + ""); } //5.记录当前action方法的实际参数 ParameterDescriptor[] dics = filterContext.ActionDescriptor.GetParameters(); foreach(ParameterDescriptor dic in dics) { //打印action参数名称 filterContext.HttpContext.Response.Write("记录当前action方法的实际参数:" + dic.ParameterName.ToString() + ""); } base.OnActionExecuting(filterContext);}////// 执行代码后执行/// /// public override void OnActionExecuted(ActionExecutedContext filterContext){ base.OnActionExecuted(filterContext);}////// 返回结果前执行/// /// public override void OnResultExecuting(ResultExecutingContext filterContext){ base.OnResultExecuting(filterContext);}////// 返回结果后执行/// /// public override void OnResultExecuted(ResultExecutedContext filterContext){ base.OnResultExecuted(filterContext);}
异常过滤器:HandleErrorAttribute
public override void OnException(ExceptionContext filterContext){ //1.获取异常对象 Exception ex= filterContext.Exception; //2.将异常写入日志 //2.1写入记录日志的具体实现过程略... //3.告诉mvc框架,过滤器已处理异常,不需要额外处理 filterContext.ExceptionHandled = true; base.OnException(filterContext);}
配置错误页:
12 3 4