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

1
  • 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. stackoverflow.com/questions/5339621/… Commented Jul 9, 2014 at 23:00

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the links, "You should not maintain any internal state in an ActionFilter.", I wasn't aware of that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.