1.新建一个过滤器,继承ActionFilterAttribute,然后重写
public class DemoFilterAttribute:ActionFilterAttribute { //在Action执行之前执行 public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.HttpContext.Response.Write("action之前"); base.OnActionExecuting(filterContext); } //在Action执行之后执行 public override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.HttpContext.Response.Write("action之后"); base.OnActionExecuted(filterContext); } //在Result执行之前执行 public override void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.HttpContext.Response.Write("Result之前"); base.OnResultExecuting(filterContext); } //在Reuslt执行之后执行(就是方法中的代码走完之后) public override void OnResultExecuted(ResultExecutedContext filterContext) { filterContext.HttpContext.Response.Write("Result之后"); base.OnResultExecuted(filterContext); } }
然后在要进行过滤的控制器或方法上打上该特性标签
public class AjaxDemoController : Controller { EFDemo.OAEntities db = new EFDemo.OAEntities(); // GET: AjaxDemo [DemoFilter] public ActionResult Index() { return View(); } }
2.新建一个控制器,在控制器内重写OnActionExecuting方法,然后让要进行过滤的控制器继承它
public class BaseController : Controller { /// <summary> /// 在执行控制器中方法前先执行该方法 /// </summary> /// <param name="filterContext"></param> protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); if (Session["userInfo"] == null) { filterContext.HttpContext.Response.Redirect("/Login/Index"); } } }
public class UserInfoController :BaseController //Controller { }
时间: 2024-12-15 18:38:55