I have been doing some testing with the following code to try and work out how ActionFilterAttributes works:
public class TestAttribute : ActionFilterAttribute
{
private string _privateValue;
public string PublicValue { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
_privateValue = DateTime.Now.ToString();
base.OnActionExecuting(filterContext);
}
}
When I run the above code on two parallel threads the _privateValue field gets confused. However the PublicValue property doesn’t get confused.
It looks to me like ActionFilterAttributes are reused across threads, but that new instances are created depending on the constants specified to public properties. Am I correct?
Where can I find information on this?
This will depend on the version of ASP.NET MVC but you should never store instance state in an action filter that will be reused between the different methods. Here’s a quote for example from one of the breaking changes in ASP.NET MVC 3:
This basically means that the same instance of the action filter can be reused for different actions and if you have stored instance state in it it will probably break.
And in terms of code this means that you should absolutely never write an action filter like this:
but you should write it like this: