Search code examples
asp.net-mvcasp.net-mvc-3action-filter

Improperly stored instance state in Action Filter


I just upgraded my project from ASP.NET MVC1.0 to ASP.NET MVC4.0

One thing that realy frightens me is the the following sentence on the upgrade documentation to MVC3.0

In previous versions of ASP.NET MVC, action filters are create per request except in a few cases. This behavior was never a guaranteed behavior but merely an implementation detail and the contract for filters was to consider them stateless. In ASP.NET MVC 3, filters are cached more aggressively. Therefore, any custom action filters which improperly store instance state might be broken.

I think there is no easy way to test for errors caused by improperly stored instance state . If I have an issue am pretty confident that I will only find it in production.

What does improperly stored instance state realy mean here?

I have this code:

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

Is this a sample of improperly stored instance state?


Solution

  • No, your code snippet is fine. Improperly stored state would be some class level properties eg:

    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.
        ...
      }
    }