Action过滤器
/// <summary> /// 执行代码前执行 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { //1.显示触发过滤器action方法的名称 string actionName = filterContext.ActionDescriptor.ActionName; filterContext.HttpContext.Response.Write("ActionName=" + actionName + "</br>"); //2.显示触发过滤器action方法所在的控制器 string ctrlName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; filterContext.HttpContext.Response.Write("ControllerName=" + ctrlName + "</br>"); //3.判断当前action方法是否贴有[HttpGet]特性标签 bool isTrue = filterContext.ActionDescriptor.IsDefined(typeof(HttpGetAttribute), false); filterContext.HttpContext.Response.Write("当前action是否贴有[httpGet]特性" + isTrue + "</br>"); //4.获取当前action方法上贴有[HttpGet]特性标签的实例 object[] httpGets = filterContext.ActionDescriptor.GetCustomAttributes(typeof(HttpGetAttribute), false); foreach (object obj in httpGets) { filterContext.HttpContext.Response.Write("获取当前action方法上贴有[HttpGet]特性标签的实例:" + obj.ToString() + "</br>"); } //5.记录当前action方法的实际参数 ParameterDescriptor[] dics = filterContext.ActionDescriptor.GetParameters(); foreach(ParameterDescriptor dic in dics) { //打印action参数名称 filterContext.HttpContext.Response.Write("记录当前action方法的实际参数:" + dic.ParameterName.ToString() + "</br>"); } base.OnActionExecuting(filterContext); } /// <summary> /// 执行代码后执行 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); } /// <summary> /// 返回结果前执行 /// </summary> /// <param name="filterContext"></param> public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); } /// <summary> /// 返回结果后执行 /// </summary> /// <param name="filterContext"></param> 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); }
配置错误页:
1 <customErrors mode="On" defaultRedirect="Error"> 2 <error statusCode="404" redirect="~/ErrorMgr/P404" /> 3 <error statusCode="500" redirect="~/ErrorMgr/P500"/> 4 </customErrors>