ASP.NET MVC的Action拦截器(过滤器)ActionFilter
有时项目要进行客户端请求(action)进行拦截(过滤)验证等业务,可以使用拦截器进行实现,所谓的action拦截器也没有什么的,只是写一个类,继承另一个类(System.Web.Mvc.FilterAttribute)和一个接口(System.Web.Mvc.IActionFilter),至于什么是拦截器这里就不说了,网上很多关于这方面文章。
假如现在有这样的一个需求:某个action需要登录才能进行访问,可以使用action属性拦截器进行拦截进行验证
多余的不说了直接上代码
写一个拦截器类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 namespace AttributeDemo.Common 8 { 9 /// <summary> 10 /// Action拦截器 11 /// </summary> 12 public class ActionFilterAttribute : System.Web.Mvc.FilterAttribute, System.Web.Mvc.IActionFilter 13 { 14 #region 属性 15 /// <summary> 16 /// 记录是否登陆 17 /// </summary> 18 public bool IsLogin { get; set; } 19 #endregion 20 21 #region 执行action后执行这个方法 22 /// <summary> 23 /// 执行action后执行这个方法 24 /// </summary> 25 /// <param name="filterContext"></param> 26 void System.Web.Mvc.IActionFilter.OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext) 27 { 28 29 } 30 #endregion 31 32 33 #region 执行action前执行这个方法 34 /// <summary> 35 /// 执行action前执行这个方法 36 /// </summary> 37 /// <param name="filterContext"></param> 38 void System.Web.Mvc.IActionFilter.OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) 39 { 40 41 if (!this.IsLogin) //未登陆 重定向 到登陆页面 42 { 43 if (filterContext.HttpContext.Request.IsAjaxRequest()) //判断是否ajax请求 44 { 45 46 filterContext.Result = new System.Web.Mvc.JsonResult() { Data = new { statusCode = 301 }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet, ContentType = "json" }; 47 return; 48 } 49 else //验证不通过 50 { 51 //filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "ActionFilterTest", action = "Login" })); //重定向 52 //filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new Dictionary<string, object>() { { "controller", "ActionFilterTest" }, { "action", "Login" } })); //重定向 53 54 //filterContext.Result = new System.Web.Mvc.RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary(new Dictionary<string, object>() { { "controller", "ActionFilterTest" }, { "action", "Login" } })); //重定向 55 56 //filterContext.Result = new System.Web.Mvc.RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary(new Dictionary<string, object>() { { "controller", "ActionFilterTest" }, { "action", "Login" } }),true); //重定向 57 58 filterContext.Result = new System.Web.Mvc.RedirectToRouteResult("MyRoute", new System.Web.Routing.RouteValueDictionary(new Dictionary<string, object>() { { "controller", "ActionFilterTest" }, { "action", "Login" } }), true); //重定向 59 return; 60 } 61 62 } 63 64 } 65 #endregion 66 67 } 68 }
请求的控制器类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 namespace AttributeDemo.Controllers 8 { 9 /// <summary> 10 /// 测试Action拦截器 11 /// </summary> 12 public class ActionFilterTestController : Controller 13 { 14 // 15 // GET: /ActionFilterTest/ 16 17 /// <summary> 18 /// 测试action拦截器 19 /// </summary> 20 /// <returns></returns> 21 [AttributeDemo.Common.ActionFilter(IsLogin = false)] 22 public ActionResult Test() 23 { 24 return View(); 25 } 26 27 28 public ActionResult Login() 29 { 30 return View(); 31 } 32 33 [AttributeDemo.Common.ActionFilter(IsLogin = true)] 34 public ActionResult Index() 35 { 36 return View(); 37 } 38 } 39 }
Global.asax类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using System.Web.Routing; 7 8 namespace AttributeDemo 9 { 10 // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明, 11 // 请访问 http://go.microsoft.com/?LinkId=9394801 12 13 public class MvcApplication : System.Web.HttpApplication 14 { 15 public static void RegisterGlobalFilters(GlobalFilterCollection filters) 16 { 17 filters.Add(new HandleErrorAttribute()); 18 } 19 20 public static void RegisterRoutes(RouteCollection routes) 21 { 22 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 23 24 routes.MapRoute( 25 "Default", // 路由名称 26 "{controller}/{action}/{id}", // 带有参数的 URL 27 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值 28 ); 29 routes.MapRoute( 30 "MyRoute", // 路由名称 31 "{controller}/{action}/{id}", // 带有参数的 URL 32 new { controller = "ActionFilterTest", action = "Login", id = UrlParameter.Optional } // 参数默认值 33 ); 34 } 35 36 protected void Application_Start() 37 { 38 AreaRegistration.RegisterAllAreas(); 39 40 RegisterGlobalFilters(GlobalFilters.Filters); 41 RegisterRoutes(RouteTable.Routes); 42 } 43 } 44 }
注意:拦截器也可以写在控制器类属性上,写在控制器类上表示拦截该控制器下所有action,如果写在action只是拦截当前action有效
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AttributeDemo.Controllers { /// <summary> /// 测试Action拦截器 /// </summary> [AttributeDemo.Common.ActionFilter(IsLogin = false)] public class ActionFilterTestController : Controller { // // GET: /ActionFilterTest/ } }