Search code examples
asp.netsessionazureiishttpmodule

Access session in HttpModule in or after Response.Filter?


I'm using Azure session state provider (DistributedCacheSessionStateStoreProvider) and it works great. But now I have a custom HttpModule that combines scripts. I'm hooking Response.Filter in PostAcquireRequestState. I'm then sending Session reference to my custom filter via a constructor:

application.Response.Filter = new CombinationFilter(application.Response.Filter, application, application.Session)

modify Session in my filter and it works perfectly on a localhost (standard session provider). But published on Azure when I modify the Session the values are there, but later they disappear (they're not persisted). Only those added in a filter disappear, those that were there before are still there. I suspect the last synchronization is within ReleaseRequestState (based on name). This is obviously before my Response.Filter is processed.

  1. How can I access Session later in the chain and still store it?

  2. Or can I somehow use filter before ReleaseRequestState?


Solution

  • I've finally solved it. For other people that might wonder how to achieve this:

    application.PostRequestHandlerExecute += (sender, args) =>
    {
        if (YourCondition)
        {
            // performs premature flush to force the filter
            application.Response.Flush();
            String content = ((CombinationFilter) application.Response.Filter).OriginalContent;
    
            // we need to remove the filter to not execute twice
            application.Response.Filter = null;
    
            // do my stuff here, we still have a Session and also the original content
            // the content is stored on a filter in Flush() method before modification 
            // (by me => my custom property)
    
            // do not write any other content
            application.Response.SuppressContent = true;
    
            // onwards it still saves Session in ReleaseRequestState (presumably)
        }
    };