Guidance on CacheResponseAttribute and User Impersonation

Is there a way to globally include current sessionid in the cached response keys? We are allowing user impersonation but the cached response(s) are being returned for content returned for the user before the impersonation happens.

Is the best option to remove the CachedResponseAttribute and manually manage it ourselves, something like below?

var cacheKey = "unique_key_for_this_request"; //maybe SessionID + ResponsDtoType?
        return base.Request.ToOptimizedResultUsingCache(base.Cache,cacheKey,()=> 
            {
                //Delegate is executed if item doesn't exist in cache 
                //Any response DTO returned here will be cached automatically
            });

If you’re asking how you can have different content cached for different users you can use VaryByUser, if you’re instead asking to use a different user session Id other than the one that’s assigned to the request then you would need to manage the custom cache keys yourself. The CacheResponseAttribute does allow for some advanced customization that does let you easily append to the cache key used.

Aha. Looks like VaryByUser will work. I assume the user identified by the X-UAId cookie value?

It uses the Session Id for the request, commonly specified in the Request’s Cookies.

1 Like