2

I have an attribute on a controller, controller action:

    [InitialisePage(new[]{PageSet.A, PageSet.B})]
    public ActionResult Index()
    {
         ...
    }

attribute:

    public class InitialisePageAttribute : FilterAttribute, IActionFilter
    {
        private List<PageSet> pageSetList = new List<PageSet>();

        public InitialisePageAttribute(PageSet pageSet)
        {
            this.pageSetList.Add(pageSet);
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            MySettings.GetSettings().InitialiseSessionClass(pageSetList);
        }
}

When the action is called for the second time the constructor for the attribute isn't called? It just goes straight to the OnActionExecuting method, the pageSet list is still set.

I guess these are cached, where are they cached? Is this optional behavior?

thanks

tony
  • 2,178
  • 2
  • 23
  • 40
  • It is interesting to note that attributes are 'baked' in to your assembly. So I wouldnt know if that has anything to do with it. http://stackoverflow.com/questions/5339621/asp-net-mvc-add-hiddeninput-attribute-to-model-in-dll – AmmarCSE Jul 09 '14 at 23:00

1 Answers1

3

Try setting the following in you OnActionExecuting to prevent caching:

filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();

Prevent Caching in ASP.NET MVC for specific actions using an attribute

However, according to

Authorize Attribute Lifecycle

ASP.NET will cache ActionFilter attributes. So you may not be able to call the constructor more than once and will instead will have to refactor your code for maintaining the attribute state.

Update

You may be able to controll this by setting the cache policy:

protected void SetCachePolicy( AuthorizationContext filterContext )
{
    HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
    cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
    cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
}

Prevent Caching of Attributes in ASP.NET MVC, force Attribute Execution every time an Action is Executed

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • 1
    Thanks for the links, "You should not maintain any internal state in an ActionFilter.", I wasn't aware of that – tony Jul 10 '14 at 06:36