ASP.NET MVC使用过滤器进行权限控制
1.新建MVC项目
2.找到Models文件夹,新建 LoginCheckFilterAttribute 类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class LoginCheckFilterAttribute : ActionFilterAttribute 2 { 3 public bool IsCheck { get; set; } 4 5 public override void OnActionExecuting(ActionExecutingContext filterContext) 6 { 7 base.OnActionExecuting(filterContext); 8 9 if (IsCheck) 10 { 11 //校验用户是否已经登录 12 if (filterContext.HttpContext.Session["loginUser"] == null) 13 { 14 filterContext.HttpContext.Response.Redirect("/UserLogin/Index"); 15 } 16 } 17 18 filterContext.HttpContext.Response.Write("开始时间:" + DateTime.Now.ToString() + "<br/>"); 19 } 20 21 public override void OnActionExecuted(ActionExecutedContext filterContext) 22 { 23 base.OnActionExecuted(filterContext); 24 var controllerName = filterContext.RouteData.Values["controller"].ToString(); 25 var actionName = filterContext.RouteData.Values["action"].ToString(); 26 filterContext.HttpContext.Response.Write("结束时间:" + DateTime.Now.ToString() + "<br/>"); 27 filterContext.HttpContext.Response.Write("controller:" + controllerName + ",action:" + actionName); 28 } 29 }
3.找到App_Start下的 FilterConfig.cs 添加以下代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class FilterConfig 2 { 3 public static void RegisterGlobalFilters(GlobalFilterCollection filters) 4 { 5 filters.Add(new HandleErrorAttribute()); 6 7 filters.Add(new LoginCheckFilterAttribute() { IsCheck = true }); 8 } 9 }
4.使用方式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 [LoginCheckFilter(IsCheck = false)] 2 public class UserLoginController : BaseController 3 { 4 public UserLoginController() 5 { 6 this.IsCheckLogin = false; 7 } 8 // 9 // GET: /UserLogin/ 10 11 [LoginCheckFilter(IsCheck = true)] 12 public ActionResult Index() 13 { 14 return View(); 15 } 16 }
End
1.扩展基类进行权限控制
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class BaseController : Controller 2 { 3 //在当前控制器所有方法之前执行,都先执行此代码 4 public bool IsCheckLogin = true; 5 6 protected override void OnActionExecuting(ActionExecutingContext filterContext) 7 { 8 base.OnActionExecuting(filterContext); 9 10 if (IsCheckLogin) 11 { 12 //校验用户是否已经登录 13 if (filterContext.HttpContext.Session["loginUser"] == null) 14 { 15 filterContext.HttpContext.Response.Redirect("/UserLogin/Index"); 16 } 17 } 18 } 19 }
2.调用方式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class UserLoginController : BaseController 2 { 3 public UserLoginController() 4 { 5 this.IsCheckLogin = false; 6 } 7 }