mvc 过滤器
1.mvc 过滤器分为 授权-行为-异常
2.授权,自定义授权。先走OnAuthorization,然后内部调用AuthorizeCore方法,如果返回true 就跳转指定的路径,如果返回false 就内部跳转到授权异常HandleUnauthorizedRequest方法。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace 过滤器.Filter { public class MYAuthorization : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); } protected override bool AuthorizeCore(HttpContextBase httpContext) { var v=CookieHelper.GetCookie("aa"); if (v == "") { return false; } else { return true; } } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { //filterContext.Result = new JsonResult() { Data = new { AuthorizeMessage = "您需要登陆"}, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; filterContext.Result = new RedirectResult("/Login/Index?ReturnUrl=" + filterContext.HttpContext.Request.Url.ToString().Replace(filterContext.HttpContext.Request.Url.Port.ToString(), string.Empty)); } protected override HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) { string l = "sss"; return HttpValidationStatus.Invalid; } } }
3.异常筛选器
只要是有报错就会走这个方法,并且会跳转到指定的页面
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace 过滤器.Filter { public class MYHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if (!filterContext.ExceptionHandled) { filterContext.ExceptionHandled = true; filterContext.Result = new ViewResult() { ViewName = "/Views/Shared/MyError.cshtml" }; } } } }
4.行为过滤器
MYActionFilter
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace 过滤器.Filter { public class MYActionFilter : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { } public override void OnActionExecuting(ActionExecutingContext filterContext) { } public override void OnResultExecuted(ResultExecutedContext filterContext) { } public override void OnResultExecuting(ResultExecutingContext filterContext) { } } }