原想在 MVC Action 上加一个自定义 Attribute 来做一些控制操作,最先的做法是在自定 Attribute 中定义一个属性来做逻辑判断,可惜事与愿违,这个属性值居然会被缓存起来,于是于此做个笔记以免后续重蹈覆辙。


过滤器部分

过滤器中定义了一个名称为 count 的属性值来初始化,并重写了 OnActionExecuting 方法

让 count 属性进行累加的操作。

  1 public class TestFilterAttribute : ActionFilterAttribute
  2 {
  3     public int count = 0;
  4 
  5     public override void OnActionExecuting(ActionExecutingContext filterContext)
  6     {
  7         count = count + 1;
  8 
  9         filterContext.HttpContext.Items.Add("count", count);
 10 
 11         base.OnActionExecuting(filterContext);
 12     }
 13 }


控制器部分

控制器 Action 中主要是获取并显示过滤器中传递的 count 属性,我预期的结果是 1 + 1 = 2,果然不负所望,第一次运行的结果果真是 2

但是如果再尝试访问该 Action 其值却出乎预期开始了累加...

  1 [TestFilter(count = 1)]
  2 public ActionResult TestJson()
  3 {
  4     var count = (int)HttpContext.Items["count"];
  5 
  6     return Json(count, JsonRequestBehavior.AllowGet);
  7 }


结果猜想

猜测过滤器可能作为一个单例存在于内存,提供给 Action 调用前访问

到底底层是如何实现或者设计,就不去探讨了,先记下笔记告诫自己。


自行验证

没找出个所以然,心里还是有些阻塞

故而去看了下 IL 代码,结果一目了然

【MVC 笔记】MVC 自定义 Attribute 属性中的猫腻


再者,Attribute 在编译时就已经被实例化

(所以我们可以通过 Attribute.GetCustomAttribute(typeof(Class), typeof(Attribute)) 在未实例化类时获取 Attribute 信息

不像其它类运行时实例化,上图 IL 也清晰给出了说明

相关文章:

  • 2021-10-15
  • 2021-07-16
  • 2022-12-23
  • 2021-10-12
  • 2021-11-16
  • 2021-08-11
  • 2021-05-14
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
  • 2021-08-28
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案