过滤器 继承AuthorizeAttribute类,实现 AuthorizationFilter(授权/最先执行),IActionFilter(行为/方法前后),IResultFilter(结果/视图渲染/),IExceptionFilter(异常)接口
public class MyFilter : AuthorizeAttribute, IAuthorizationFilter,IActionFilter,IResultFilter,IExceptionFilter { void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext) { if(System.Web.HttpContext.Current.Session["userName"]==null) { filterContext.Result = new RedirectResult("Home/Index"); } filterContext.HttpContext.Response.Write("方法前后"); filterContext.HttpContext.Response.Redirect("error");//异常 } }
例如校验登录过滤器
/// <summary> /// 校验登录过滤器 /// </summary> public class CheckIsLogin : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if (HttpContext.Current.Session["userInfo"] == null) { filterContext.Result = new RedirectResult("/Login/Login"); } } }