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

时间:2012-01-04 10:07:10

标签: asp.net-mvc asp.net-mvc-3 action-filter

我刚刚将我的项目从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;
}

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

1 个答案:

答案 0 :(得分: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.
    ...
  }
}