在Action Filter中存储的实例状态不正确

Mat*_*s F 4 asp.net-mvc action-filter asp.net-mvc-3

我刚刚将我的项目从ASP.NET MVC1.0升级到ASP.NET MVC4.0

令我真正害怕的一件事就是MVC3.0升级文档中的以下句子

在以前版本的ASP.NET MVC中,除少数情况外,每个请求都会创建操作过滤器.这种行为从来都不是保证行为,而只是一个实现细节,而过滤器的合同是将它们视为无状态.在ASP.NET MVC 3中,过滤器被更积极地缓存.因此,任何不正确地存储实例状态的自定义操作过滤器都可能被破坏.

我认为没有简单的方法来测试由不正确存储的实例状态引起的错误.如果我有一个问题,我非常有信心,我只能在生产中找到它.

不正确存储的实例状态真正意味着什么?

我有这个代码:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   ProductModel productModel = new ProductModel()
   filterContext.ActionParameters["model"] = productModel;
}
Run Code Online (Sandbox Code Playgroud)

这是不正确存储的实例状态的示例吗?

Ric*_*lly 5

不,你的代码片段没问题.存储不正确的状态将是某些类级属性,例如:

public class StatefulActionFilter : ActionFilter
{
  private readonly IPrincipal currentPrincipal = Thread.CurrentPrincipal;

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    ...
    // Using currentPrincipal here would be bad, since it may refer to the principal of a previous request.
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)