MVC支持的过滤器类型有四种,分别是:Authorization(授权),Action(行为),Result(结果)和Exception(异常)
自定义Action,代码是视频里面的,先记录,后面用到再做深入
namespace MvcValidateDemo.Models { //AllowMultiple = true:允许多个标签同时都起作用 [AttributeUsage(AttributeTargets.All,AllowMultiple = true)] public class MyActionFilterAttribute : ActionFilterAttribute { public string Name { get; set; } //Action 执行之前先执行此方法 public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); //HttpContext.Current.Session[""] HttpContext.Current.Response.Write("<br />OnActionExecuting :" + Name); } //Action执行之后 public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HttpContext.Current.Response.Write("<br />OnActionExecuted :" + Name); } //ActionResult执行之前先执行此方法 public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); HttpContext.Current.Response.Write("<br />OnResultExecuting :" + Name); } public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); HttpContext.Current.Response.Write("<br />OnResultExecuted :" + Name); } } }
整个控制器执行了 [MyActionFilter(Name = "Controller action")]
public class PatialController : Controller { // // GET: /Patial/ //打上过滤器的标签 [MyActionFilter(Name = "index action")] public ActionResult Index() { return View(); }
//打上过滤器的标签 [MyActionFilter(Name = "About action")]
public ActionResult About()
{
ViewData["key"] = "Action 执行了";
ViewBag.Demo = "Action bag 执行了";
return View(); }
}
2.全局过滤器变量
FilterConfig打开,表示所有的控制器和action都执行了这个过滤器
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new MyExceptionFilterAttribute()); //全局过滤器,优先级最低,但是可以作用到所有的控制器和action //filters.Add(new MyActionFilterAttribute(){Name = "Gloable"}); } }
3,
public class MyExceptionFilterAttribute: HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //当出现了异常的时候,才执行此方法 //记录日志多个线程同时访问一个日志文件性能非得低。 //考虑使用内存队列提高性能,Redis //加入观察者模式屏蔽写入不同地方的变化点 loge4net //页面跳转到错误页面或者是首页 HttpContext.Current.Response.Redirect("/Home/Index"); } }
你将独自前行,你会遇到友好,也会遇到恶意,不管你多么善良,因为世间就是这样,不好,不坏.